我在用BeautifulSoup4和Python3抓取网站时遇到了问题。我使用dryscrape来获取HTML,因为它需要启用JavaScript才能显示(但据我所知,它从未在页面中使用过)。在
这是我的代码:
from bs4 import BeautifulSoup
import dryscrape
productUrl = "https://www.mercadona.es/detall_producte.php?id=32009"
session = dryscrape.Session()
session.visit(productUrl)
response = session.body()
soup = BeautifulSoup(response, "lxml")
container1 = soup.find("div","contenido").find("dl").find_all("dt")
container3 = soup.find("div","contenido").find_all("td")
现在我想阅读container3
内容,但是:
退货:
bs4.element.ResultSet
它与type(container1)
相同,但它的长度是0!在
所以我想知道在查找我的<td>
标记之前,我得到了container3
的什么,所以我把它写到了一个文件中。在
container3 = soup.find("div","contenido")
soup_file.write(container3.prettify())
下面是指向该文件的链接:https://pastebin.com/xc22fefJ
就在我要刮桌子之前,一切都搞砸了。我不明白为什么,看看Firefox的URL源代码,一切看起来都很好。在
以下是更新的解决方案:
对此的响应给出
^{pr2}$Please enable JavaScript to view the page content.
消息。但是,它还包含浏览器使用javascript发送的必要的hidden
数据,可以从开发人员工具的network选项卡中看到。在其中,第二个(长字符串)是由javascript生成的。我们可以使用
js2py
这样的库来运行代码,它将返回请求中传递的所需字符串。在结果如下:
编辑
显然,javascript代码只需要运行一次。结果数据可用于多个请求,如下所示:
结果:
相关问题 更多 >
编程相关推荐