问 题
如图所示,用python爬取的html页面和浏览器显示的内容有些出入。
照理说爬取的同样是服务器端静态的html页面,怎么会有不同呢?
网站地址:点我点我
爬虫源码:
# -*-coding:UTF-8-*-
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://www.pythonscraping.com/pages/page3.html")
bsObj = BeautifulSoup(html,"lxml")
for child in bsObj.find("",{"id": "giftList"}).contents:
print(child)
这个问题可能有点“孔乙己”,不过我确实挺好奇它的原因的,希望有人能不吝赐教
解决方案
经过实测,结论是 bs4 改变了属性的顺序。
1、在浏览器中右键点击页面,选:
审查元素
查看网页源码
2、在 python3 程序中对比:
import re
ptn_tr = re.compile(r'
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:
urlopen:
bs4Soup:
扫一扫关注IT屋
微信公众号搜索 “ IT屋 ” ,选择关注与百万开发者在一起