glidedsky爬虫闯关 第一关

今天无意中发现了一个练习爬虫的网站:
http://glidedsky.com/

做的挺不错的 强烈推荐

第一关是将网页中所有的数字相加,因为格式十分整齐,可以用多种方法来实现,一并记录在这里了,注意在get的时候要加上在cookie

import requests
from bs4 import BeautifulSoup
import re
from requests_html import HTMLSession
from lxml import etree

header = {"cookie": "自己的cookie"}
r=requests.get("http://glidedsky.com/level/web/crawler-basic-1",headers=header)

r.encoding = r.apparent_encoding
html = BeautifulSoup(r.text,'lxml')
anss=0

#css选择器
x=html.select("div[class='col-md-1']")
for i in x:
    anss+=int(i.get_text().strip())
print(anss)

"""
#正则
s='''<div class="col-md-1">(.+?)</div>'''
x=re.findall(s,r.text,re.DOTALL)
for i in x:
    anss+=int(i.strip())
print(anss)
"""

"""
#HTMLSession.get().html.find()方法
session=HTMLSession()
url=session.get("http://glidedsky.com/level/web/crawler-basic-1",headers=header)
#content=url.html.find('div.col-md-1:nth-child(1)',first=True)
for i in range(1,1201):
    s='div.col-md-1:nth-child('+str(i)+')'
    content=url.html.find(s,first=True)
    anss+=int(content.text)
print(anss)
"""

"""
#xpath路径
label=etree.HTML(r.text)
content=label.xpath('//div[@class="col-md-1"]/text()')
#提取div标签中class名为"col-md-1"的内容信息,并且存入一个列表中
for i in content:
    anss+=int(i.replace('\n', '').strip())
print(anss)
"""

猜你喜欢

转载自www.cnblogs.com/dyhaohaoxuexi/p/12466290.html