脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python用requests库爬取返回为空的解决办法

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

2021-09-07 00:38qq_38796636 Python

这篇文章主要介绍了Python用requests库爬取返回为空的解决办法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

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

我们要爬取的内容:

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

html字段:

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

robots协议:

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

现在我们开始用python idle 爬取

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

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

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

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

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

?
1
2
3
4
5
6
7
8
9
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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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])

得到结果如下:

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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库爬取返回为空的解决办法的文章就介绍到这了,更多相关python requests返回为空内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/qq_38796636/article/details/95223267

延伸 · 阅读

精彩推荐