网页爬虫 - 【如图】python爬取的html页面和浏览器显示源码的结果不同
高洛峰
高洛峰 2017-04-18 09:31:41
0
4
768
高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

Antworte allen(4)
伊谢尔伦

经过实测,结论是 bs4 改变了属性的顺序。

1、在浏览器中右键点击页面,选:

审查元素

查看网页源码

2、在 python3 程序中对比:

import re
ptn_tr = re.compile(r'<tr[^>]+>')

import requests as req
rsp=req.get('http://www.pythonscraping.com/pages/page3.html')
html = rsp.text
print('requests:\t', ptn_tr.findall(html)[0])

from urllib.request import urlopen
rsp = urlopen("http://www.pythonscraping.com/pages/page3.html")
html = rsp.read().decode()
print('urlopen:\t', ptn_tr.findall(html)[0])

from bs4 import BeautifulSoup
html = str(BeautifulSoup(html,"lxml"))
print('bs4Soup:\t', ptn_tr.findall(html)[0])

结果:

requests:     <tr id="gift1" class="gift">
urlopen:     <tr id="gift1" class="gift">
bs4Soup:     <tr class="gift" id="gift1">
阿神

class和id顺序不一样而已,
你用chrome和firefox查看同一个网页源代码,顺序也是不一样的.

小葫芦

建议题主把网站甚至自己的代码贴出来,方便大家帮你调试。不一样很正常,如果你爬虫爬下来的内容保存为静态页面,和你用浏览器看到的不一样,那么肯定是对对方反爬虫机制给识别了,所以服务器会返回不同的信息。识别爬虫的方法很多,题主如果还有疑惑欢迎再问

巴扎黑

楼主建议你贴出全部源代码,因为网站可以识别你是人工浏览器操作还是爬虫。

目前代码来看,建议你增加头部信息!use-agent 那行代码!

Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage