前言:有过一些自学爬虫的经历,但都是很小的爬虫。
步骤如下:
1、解析页面
打开街拍页面图集,重新加载,发现又回到综合的那页。
审查元素,找到network,发现并没有返回街拍那页的源代码。点开XHR,headers里面查看,可看见keyword为街拍,再点开preview,点开data,可以看见data的title对应上了页面数据。
2、代码编写
def get_page_index(offset,keyword): #第一步:解析html,得到json数据
data = {
'offset': offset,
'format': 'json',
'keyword': keyword,
'autoload': 'true',
'count': 20,
'cur_tab': 1
}
url = 'https://www.toutiao.com/search_content/?'+ urlencode(data)
try:
response = requests.get(url)
if response.status_code == 200:
return response.text
return None
except RequestException:
print('请求页面失败')
def main(): #编写main函数
html = get_page_index(0,'街拍')
print(html)
def parse_page_index(html): #第二步: 分析json,得到页面url
data = json.loads(html)
if data and 'data' in data.keys():
for item in data.get('data'):
yield item.get('article_url')