BeautifulSoup中的一些问题
使用wkpdftohtml将爬取到的网页生成PDF时,使用示例代码
import requests from bs4 import BeautifulSoup import pdfkit url = 'http://www.liaoxuefeng.com/wiki/' \ '001434446689867b27157e896e74d51a89c25cc8b43bdb3000' response = requests.get(url) bsObj = BeautifulSoup(response.content, 'xml') body = bsObj.findAll(class_='x-wiki-content') html = str(body) html = html.encode('utf-8') fp = open('test.html', 'wb') fp.write(html) fp.close() fp = open('test.pdf', 'wb') fp.close() pdfkit.from_file('test.html', 'test.pdf')
出现警告
Warning: A finished ResourceObject received a loading progress signal. This might be an indication of an iframe taking too long to load
并且没有得到预想中的PDF文件。(代码块访问的是廖雪峰的js教程网站)
将beautifulsoup中的解析器换成"lxml"或“html.parser则能够生成预期的PDF文件
阅读BeautifulSoup的文档
根据beautifulsoup的文档,不同的解析器之前对文本的解析是存在区别的参见beautifulsoup文档
使用xml解析器致使生成的dom树与理想的不同(不是bug,是不同解析器的处理机制),以至于停止生成pdf。