使用 BeautifulSoup 导航

Navigation with BeautifulSoup

我对如何使用 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. 有没有办法通过标签只找到particular href?例如,我想要的所有 href 都由某个名称调用,例如price 在在线目录中。

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

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

有了 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.

比如说,你需要的所有 link 文本中都有 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 and many other different kind of objects to filter elements, like, for example, compiled 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"])

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

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

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

如果我没理解错的话,你需要得到合适的links,跟着他们把页面的源代码保存到本地的HTML文件中。根据您的要求,有多个选项可供选择(例如,速度可能很关键。或者,这只是一次性任务,您不关心性能)。

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

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)

您可以查看 grequests or Scrapy 来解决该部分。