我对如何使用 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")
有没有办法通过标签只找到特定的
href
?例如,我想要的所有href
都由某个名称调用,例如在线目录中的price
。我想要的
href
链接都在网页的某个位置,在页面的和某个 .我可以只访问这些 链接吗?如何抓取每个
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)
关于python - 使用 BeautifulSoup 导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33404049/