网页爬虫 - 【如图】python爬取的html页面和浏览器显示源码的结果不同

查看:1250
本文介绍了网页爬虫 - 【如图】python爬取的html页面和浏览器显示源码的结果不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

如图所示,用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'<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">

这篇关于网页爬虫 - 【如图】python爬取的html页面和浏览器显示源码的结果不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆