我写了一个带有请求和BeautifulSoup的网络抓取器,DOM中有一个我找不到的元素。
这是我的工作:
import requests
from bs4 import BeautifulSoup
r = requests.get('http://www.decitre.fr/rechercher/result/?q=victor+hugo&search-scope=3')
soup = BeautifulSoup(r.text)
我找不到的元素是"旧价格"(删除线的那个),当我使用浏览器开发工具检查 DOM 时,我可以看到它。
soup.find_all(class_='old-price') # returns [], no matter if I specify "span"
此外,我看不到汤中的"旧价格"字符串或请求的结果:
'old-price' in soup.text # False
'old-price' in r.text # False
当我用wget
获得源代码时,我也看不到它。
我可以得到它的div 父级,但在里面找不到价格子项:
commands = soup.find_all(class_='product_commande')
commands[0].find_all('old-price') # []
所以我不知道发生了什么。我错过了什么?
- 我是否错误地使用请求/美丽汤?(我不确定 r.text 是否返回完整的 html)
- 那个HTML部分是用JavaScript代码生成的吗?如果是这样,我怎么知道它,有没有办法获得完整的html?
非常感谢
就我而言,我将无效的HTML传递到美丽的汤中,这导致它忽略了文档开头无效标签之后的所有内容:
<!--?xml version="1.0" encoding="iso-8859-1"?-->
请注意,我也在使用Ghost.py
.这是我删除标签的方式。
#remove invalid xml tag
ghostContent = ghost.content
invalidCode = '<!--?xml version="1.0" encoding="iso-8859-1"?-->'
if ghostContent.startswith(invalidCode):
ghostContent = ghostContent[len(invalidCode):]
doc = BeautifulSoup(ghostContent)
#test to see if we can find text
if 'Application Search Results' in doc.text:
print 'YES!'