python - 使用 BeautifulSoup 导航

标签 python html beautifulsoup html-parsing python-requests

我对如何使用 BeautifulSoup 导航 HTML 树有点困惑。

import requests
from bs4 import BeautifulSoup

url = 'http://examplewebsite.com'
source = requests.get(url)
content = source.content
soup = BeautifulSoup(source.content, "html.parser")

# Now I navigate the soup
for a in soup.findAll('a'):
    print a.get("href")
  1. 有没有办法通过标签只找到特定的 href?例如,我想要的所有 href 都由某个名称调用,例如在线目录中的 price

  2. 我想要的 href 链接都在网页的某个位置,在页面的和某个 .我可以只访问这些 链接吗?

  3. 如何抓取每个 href 链接中的内容并保存为文件格式?

最佳答案

有了 BeautifulSoup,这一切都变得简单易行。

(1) Is there a way to find only particular href by the labels? For example, all the href's I want are called by a certain name, e.g. price in an online catalog.

比如说,您需要的所有链接的文本中都有 price - 您可以使用 text 参数:

soup.find_all("a", text="price")  # text equals to 'price' exactly
soup.find_all("a", text=lambda text: text and "price" in text)  # 'price' is inside the text

是的,您可以使用 functions和许多其他不同类型的对象来过滤元素,例如编译 regular expressions :

import re

soup.find_all("a", text=re.compile(r"^[pP]rice"))

如果 price 位于“href”属性中的某处,您可以使用以下 CSS selector :

soup.select("a[href*=price]")  # href contains 'price'
soup.select("a[href^=price]")  # href starts with 'price'
soup.select("a[href$=price]")  # href ends with 'price'

或者,通过 find_all():

soup.find_all("a", href=lambda href: href and "price" in href)

(2) The href links I want are all in a certain location within the webpage, within the page's and a certain . Can I access only these links?

当然,找到合适的容器并调用find_all() or other searching methods :

container = soup.find("div", class_="container")
for link in container.select("a[href*=price"):
    print(link["href"])

或者,您可以按照在具有所需属性或属性值的特定元素内搜索链接的方式编写 CSS 选择器。例如,我们在这里搜索具有 href 属性的 a 元素位于具有 container 类的 div 元素中:

soup.select("div.container a[href]")

(3) How can I scrape the contents within each href link and save into a file format?

如果我理解正确,您需要获得适当的链接,跟随它们并将页面的源代码本地保存到 HTML 文件中。根据您的要求,有多个选项可供选择(例如,速度可能很关键。或者,这只是一次性任务,您不关心性能)。

如果您继续使用 requests,代码将具有阻塞性质 - 您将提取链接,跟随它,保存页面源代码,然后继续下一个 - 主要它的缺点是它会很慢(对于初学者来说,取决于有多少链接)。示例代码助您一臂之力:

from urlparse import urljoin

from bs4 import BeautifulSoup
import requests

base_url = 'http://examplewebsite.com'
with requests.Session() as session:  # maintaining a web-scraping session
    soup = BeautifulSoup(session.get(base_url).content, "html.parser")

    for link in soup.select("div.container a[href]"):
        full_link = urljoin(base_url, link["href"])
        title = a.get_text(strip=True)

        with open(title + ".html", "w") as f:
            f.write(session.get(full_link).content)

你可以看看grequestsScrapy解决那部分。

关于python - 使用 BeautifulSoup 导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33404049/

相关文章:

javascript - 打开一个新的最小化窗口?

python - 网页抓取 : output different to original data

python - 使用 BeautifulSoup 或 minidom 解析 XML

python - 抓取具有多个链接的页面上的特定链接?

python - 如何使用 seaborn 为我的 DataFrame 创建堆叠条形图

Python-有效检查列表是否存在并且元素是否存在于列表中

python - float' 对象不能解释为整数

Python Pandas groupby 并使用分组计算 ala dplyr 改变一个新列

javascript - 使用 focus() 显示 block

javascript - 如何在 SVG 图像之间切换