因需要一些资料,就写了个爬虫爬取百度知道前N页的所有答案
不过鉴于百度知道的回答质量(你懂得。。。。),爬取的内容仅供参考
替换一下url_root和file_name基本就能通用了
注:每个网站使用的标签不一样,代码仅适用于百度知道,其他网站自行修改

# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
import lxml
url_root = 'https://zhidao.baidu.com/search?word=%C0%F8%D6%BE%B6%CC%BE%E4&ie=gbk&site=-1&sites=0&date=0&pn=0'
file_name = 'C:\\Users\\username\\Desktop\\sort_statement.txt'
# 获取下一页的url
def get_next(url):
strhtml = requests.get(url)
soup = BeautifulSoup(strhtml.text, 'lxml')
source = soup.find_all('a', class_='pager-next')
return "https://zhidao.baidu.com" + source[0]['href']
# 获取当前页的所有问答详情页url
def get_page(url):
strhtml = requests.get(url)
soup = BeautifulSoup(strhtml.text, 'lxml')
source = soup.find_all('a', class_='ti')
url_list = []
for row in source:
url_list.append(row['href'])
return url_list
# 获取问题答案
def get_answer(url):
strhtml = requests.get(url)
strhtml.encoding = 'gbk'
new_html = strhtml.text.replace('<br />', '\n').replace('<p>', '\n').replace('</p>', '\n').replace('<br>', '\n')
soup = BeautifulSoup(new_html, 'lxml')
source = soup.find_all('div', attrs={'accuse': 'aContent'})
with open(file_name, 'a', encoding='utf-8') as file_object:
for row in source:
file_object.write(row.text + '\n')
for i in range(1, 11):
url_root = get_next(url_root)
for url in get_page(url_root):
get_answer(url)
运行结果截图:

PS:
玩爬虫需谨慎,别IP被封了就不好了,可以在代码中添加sleep等措施来避免,如下图,应该是被网站认为成攻击行为了,抛出了10054异常

657



被折叠的 条评论
为什么被折叠?



