关于Python3.7的BeautifulSoup解析html文件缺失内容的问题

背景

从网站爬取html,用BeautifulSoup解析标签内容,发现用尽办法都找不到想要的标签。

分析过程

(1)把urlopen请求到的html打印出来,body是完整的;
(2)把BeautifulSoup解析后的soup打印出来,body只有少量的div,很快结束了。但后面还有一堆未格式化的html内容,被排斥在body外;
(3)一定是BeautifulSoup解析过程出问题了,由于直接请求到的html没有格式化过,太难看,copy到html在线格式化网页去格式化后再看看;
(4)对比格式化后的html和BeautifulSoup解析后的soup的内容,发现问题:soup在处理“”这样的注释时,不知道抽什么风直接结束了,在注释前面补上了body>和html>,导致缓存的soup缺失了后面大量的内容。

解决方案

注释在爬取数据过程中是无所谓的,可以用正则匹配过滤(见代码),之后就能正常解析自己想要的标签了。

代码

# -*- coding: utf-8 -*-
import urllib.request
from bs4 import BeautifulSoup
import re

import io
import sys

sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8') #改变标准输出的默认编码

user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = {'User-Agent':user_agent}
url = "https://www.amazon.com/dp/B07K97BQDF"

#导入urlopen函数
#读取网页内容,如果网页中又中文要用“utf-8”解码

req = urllib.request.Request(url, headers = headers)
html = urllib.request.urlopen(req).read()
html = html.decode('utf8').replace('\n', '').replace('\r', '')
#正则去掉注释,存在用BeautifulSoup无法解析,基于Jsoup的HMTL在线解码可以,但python似乎没有可用的
re_format = re.compile('')
html = re_format.sub('', html)
bs = BeautifulSoup(html.encode('utf8'),"html.parser")
#获取标题
product_title = bs.find('span',id="productTitle").get_text()
print(product_title.strip())

网页图片:

关于Python3.7的BeautifulSoup解析html文件缺失内容的问题_第1张图片
git下执行结果:
git下执行结果

后记

在尝试多次执行过程中会发现html仍有可能缺失or为空,再按上面的分析步骤分析的时候,发现在urlopen得到的结果就缺失了,网上搜索建议加上header(但我已经加了),后面尝试更换user_agent,问题解决了。

参考

分析过程参考:https://www.crifan.com/beautifulsoup_parse_html_fail_for_contain_special_if_statement/
后记参考:https://blog.csdn.net/weixin_42066185/article/details/81675726

你可能感兴趣的:(python)