鱼C论坛

 找回密码
 立即注册
查看: 2069|回复: 3

爬取知乎

[复制链接]
发表于 2022-5-20 13:58:09 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
各位大佬好,我想要爬取知乎某一个问题下的回答,但是好像被反爬了,不知道怎么解决,以下是我的代码
  1. import urllib.request
  2. from lxml import etree

  3. def creat_request():
  4.     url = 'https://www.zhihu.com/question/291457090/answer/572425905'
  5.     headers = {
  6.         'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36'
  7.     }

  8.     request = urllib.request.Request(url = url,headers = headers)

  9.     return request

  10. def get_content(request):
  11.     response = urllib.request.urlopen(request)

  12.     content = response.read().decode('utf-8')

  13.     return content

  14. def down_load(content):
  15.     tree = etree.HTML(content)

  16.     name_list = tree.xpath('//*[@id="QuestionAnswers-answers"]//div[@class="List-item"]//div[@class="RichContent-inner"]//p//text()')
  17.     for i in range(len(name_list)):
  18.         name = name_list[i]
  19.         print(name)
  20.     with open("攀枝花对四川的认同感.txt",'w',encoding='utf-8')as fp:
  21.         fp.write(str(name_list))



  22. if __name__ == '__main__':
  23.     request = creat_request()
  24.     content = get_content(request)
  25.     down_load(content)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2022-5-20 17:04:57 | 显示全部楼层
没有被反爬,是你的xpath写错了,去掉前面的//*[@id="QuestionAnswers-answers"]//div[@class="List-item"]
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2022-5-22 15:46:37 | 显示全部楼层
月下孤井 发表于 2022-5-20 17:04
没有被反爬,是你的xpath写错了,去掉前面的//*[@id="QuestionAnswers-answers"]//div[@class="List-item"]

修改了xpath返回的还是一个空列表啊,之前那个xpath路径我用浏览器哪个插件能够检索到想要的内容
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-5-22 20:38:14 | 显示全部楼层
我这里运行着在down_load函数里print(content)是有正确值的,xpath之后就没有了,改了xpath后运行结果都是没问题的
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-22 16:24

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表