如何使用 Beautifulsoup 抓取多个页面
有关如何使用 Beautifulsoup 抓取多个页面的分步指南。
重要提示:我们将在本教程中使用真实示例,因此你需要 要求 以及 美汤 已安装库。
步骤 1。 让我们首先导入 Beautifulsoup 库。
from bs4 import BeautifulSoup
步骤 2。 然后,导入请求库。
import requests
步骤 3。 获取目标着陆页的源代码。我们将在此示例中使用指南页面。
r=requests.get("https://proxyway.com/guides/")
普遍适用的代码如下所示:
r=requests.get("Your URL")
步骤 4。 通过查找获取下一页的链接 a 标签的类别 下页。然后,你只需要获取 HREF 从该元素开始并执行新的请求。
步骤 5。 您可以将整个代码放入一个函数中:
def scrape_page(url):
print ("URL: " + url)
r = requests.get(url)
soup = BeautifulSoup(r.content, "html.parser")
get_data(soup)
next_page_link = soup.find("a", class_="next")
if next_page_link is not None:
href = next_page_link.get("href")
scrape_page(href)
else:
print ("Done")
这是 脚本的输出。它显示您刚刚抓取的页面 URL。
让我们一步一步地看一下代码:
1.执行请求以获取页面。
r = requests.get(url)
2.解析页面并转换成BeautifulSoup对象。
soup = BeautifulSoup(r.content, "html.parser")
3. 将汤对象传递到不同的函数中,您可以在转到下一页之前抓取页面数据。
get_data(soup)
4. 寻找 下页 链接元素。
next_page_link = soup.find("a", class_="next")
5. 如果存在这样的元素,则表明您可以抓取另一个页面;如果不存在,则您已完成抓取。
if next_page_link is not None:
6. 获取 HREF 来自链接元素的属性。这是您要抓取的下一个页面的 URL。
href = next_page_link.get("href")
7. 再次调用相同的函数并将新的 URL 传递给它以抓取下一页。
scrape_page(href)
结果:
恭喜,您已使用 Beautifulsoup 抓取了多个页面。以下是完整脚本:
from bs4 import BeautifulSoup
import requests
start_url = "https://proxyway.com/guides"
def scrape_page(url):
print ("URL: " + url)
r = requests.get(url)
soup = BeautifulSoup(r.content, "html.parser")
get_data(soup)
next_page_link = soup.find("a", class_="next")
if next_page_link is not None:
href = next_page_link.get("href")
scrape_page(href)
else:
print ("Done")
def get_data(content):
#we could do some scraping of web content here
pass
def main():
scrape_page(start_url)
if __name__ == "__main__":
main()