javascript - 当抓取使用 Javascript(或许还有其他东西)的网页时

标签 javascript python html

我希望能够访问类似 this search result within a site 的网页并能够收集各种结果的链接。我使用 Python 的 urllib.request 和 bs4 来进行抓取。然而,尽我所能理解我正在查看的内容,这些链接位于某种嵌入式 Javascript 对象内部。

我尝试直接下载该页面的 HTML 源代码,试图查看它并理解它,但它下载为包含图片和各种 HTML 文件的整个文件夹,我不知道单个网页如何可以是一个文件。但我所做的是以下内容:

import urllib.request as ul
url = 'http://www.epicurious.com/tools/searchresults?search=banana'
source = ul.urlopen(url)
with open('pagesource.html', 'w') as f:
    f.write(source.read())

然后查看它生成的文档。但是,在它生成的文档中,我在搜索结果中没有看到任何指向食谱的链接。

任何人都可以告诉我页面中发生的情况以及如何收集搜索结果中的链接吗?

最佳答案

在浏览器开发人员工具中打开 HTML 并检查链接配方的 anchor 。你会发现:

<a href="/recipes/food/views/easter-bread-395055" class="recipeLnk">Easter Bread</a>

这些结果未使用 JavaScript。以下是一些基本的 Python3,可以使用 Requests 和 BeautifulSoup 获取所有食谱的链接:

import requests
from bs4 import BeautifulSoup

URL_EPICURIOUS_SEARCH="http://www.epicurious.com/tools/searchresults?search="
SEARCH_TEXT="banana"

# Run the search and get the HTML result
response = requests.get(URL_EPICURIOUS_SEARCH + SEARCH_TEXT)
if response.status_code != 200:
    print("HTTP Status:" + response.status_code)
    exit()

soup = BeautifulSoup(response.text, 'html.parser')
# Search for all links with class "recipeLink"
recipes = soup.find_all("a", class_="recipeLnk")

# Loop through the set and print all hrefs.
for recipe in recipes:
    if recipe.has_attr('href'):
        print(recipe['href'])

输出:

$ python3 recipe-search.py
/recipes/food/views/banana-pudding-356830
/recipes/food/views/banana-bread-51200430
/recipes/food/views/banana-bread-51200020
...

关于javascript - 当抓取使用 Javascript(或许还有其他东西)的网页时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33459289/

相关文章:

javascript - 单击 : handleClick

javascript - 将 SQL 命令与数据库匹配

python - 在这种情况下,一个 for 循环是否意味着 n 的时间复杂度?

jquery - 图像横幅旋转箭头

javascript - 分配给 innerHTML 时 HTML 标签会发生变化

javascript - 将任何类型的日期格式转换为 MM\DD\YYYY

javascript - PHP中的执行函数取决于Angular发送的whatsapp

Python MySQLdb : How to get the result of a sql select having a group by into a dict?

python - 如何从 Python 中的所有行和列数组中找到单个最大值并显示其行和列索引

javascript - 过渡 CSS3 在 Angular2 中不起作用?