Sha*_*ang 6 html python 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")
Run Code Online (Sandbox Code Playgroud)
有没有办法只通过标签找到特定 href的?例如,href我想要的所有内容都由某个名称调用,例如price在在线目录中.
href我想要的链接都在网页内的某个位置,在页面内和某个位置.我只能访问这些链接吗?
如何刮取每个href链接中的内容并保存为文件格式?
有了BeautifulSoup,这一切都可行而且简单.
(1)有没有办法只通过标签找到特定的href?例如,我想要的所有href都由某个名称调用,例如在线目录中的价格.
比如说,你需要的所有链接都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
Run Code Online (Sandbox Code Playgroud)
是的,您可以使用函数和许多其他不同类型的对象来过滤元素,例如,编译的正则表达式:
import re
soup.find_all("a", text=re.compile(r"^[pP]rice"))
Run Code Online (Sandbox Code Playgroud)
如果price在"href"属性中的某个位置,则可以使用以下CSS选择器:
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'
Run Code Online (Sandbox Code Playgroud)
或者,通过find_all():
soup.find_all("a", href=lambda href: href and "price" in href)
Run Code Online (Sandbox Code Playgroud)
(2)我想要的href链接都在网页内的某个位置,在页面内和某个位置.我只能访问这些链接吗?
当然,找到适当的容器和电话find_all()或其他搜索方法:
container = soup.find("div", class_="container")
for link in container.select("a[href*=price"):
print(link["href"])
Run Code Online (Sandbox Code Playgroud)
或者,您可以按照搜索具有所需属性或属性值的特定元素内的链接的方式编写CSS选择器.例如,这里我们正在搜索a具有href位于div具有container类的元素内的属性的元素:
soup.select("div.container a[href]")
Run Code Online (Sandbox Code Playgroud)
(3)如何刮取每个href链接中的内容并保存为文件格式?
如果我理解正确,您需要获取适当的链接,关注它们并将页面的源代码本地保存到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)
Run Code Online (Sandbox Code Playgroud)