• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Python用requests库爬取返回为空的解决办法

python 搞代码 4年前 (2022-01-09) 29次浏览 已收录 0个评论

首先介?一下我??用360搜索派取城市排名前20。
我们爬取的网址:https://baike.so.com/doc/24368318-25185095.html

我们要爬取的内容:

import requests
r = requests.get("https://baike.so.com/doc/24368318-25185095.html")
r.status_code
r.text

结果分析,我们可以成功访问到该网页,但是得不到网页的结果。被360搜索识别,我们将headers修改。

输出有个小插曲,网页内容很多,我是想将前500个字符输出,第一次格式错了

import requests
headers = {
  'Cookie':'OCSSID=4df0bjva6j7ejussu8al3eqo03',
  'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
         '(KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
}
r = requests.get("https://baike.so.com/doc/24368318-25185095.html", headers = headers)
r.status_code
r.text

本文来源gao!%daima.com搞$代*!码网1

接着我们对需要的内容进行爬取,用(.find)方法找到我们内容位置,用(.children)下行遍历的方法对内容进行爬取,用(isinstance)方法对内容进行筛选:

import requests
from bs4 import BeautifulSoup
import bs4
headers = {
  'Cookie':'OCSSID=4df0bjva6j7ejussu8al3eqo03',
  'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
         '(KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
}
r = requests.get("https://baike.so.com/doc/24368318-25185095.html", headers = headers)
r.status_code
r.encoding = r.apparent_encoding
soup = BeautifulSoup(r.text, "html.parser")
for tr in soup.find('tbody').children:
	if isinstance(tr, bs4.element.Tag):
		tds = tr('td')
		print([tds[0].string, tds[1].string, tds[2].string])

得到结果如下:

修改输出的数目,我们用Clist列表来存取所有城市的排名,将前20个输出代码如下:

import requests
from bs4 import BeautifulSoup
import bs4
Clist = list() #存所有城市的列表
headers = {
  'Cookie':'OCSSID=4df0bjva6j7ejussu8al3eqo03',
  'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
         '(KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
}
r = requests.get("https://baike.so.com/doc/24368318-25185095.html", headers = headers)
r.encoding = r.apparent_encoding #将html的编码解码为utf-8格式
soup = BeautifulSoup(r.text, "html.parser") #重新排版
for tr in soup.find('tbody').children:   #将tbody标签的子列全部读取
	if isinstance(tr, bs4.element.Tag):  #筛选tb列表,将有内容的筛选出啦
	  tds = tr('td')
	  Clist.append([tds[0].string, tds[1].string, tds[2].string])
for i in range(21):
  print(Clist[i])

最终结果:

到此这篇关于Python用requests库爬取返回为空的解决办法的文章就介绍到这了,更多相关Python requests返回为空内容请搜索搞代码以前的文章或继续浏览下面的相关文章希望大家以后多多支持搞代码


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python用requests库爬取返回为空的解决办法
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址