![](/img/trans.png)
[英]Looping through a list of urls for web scraping with BeautifulSoup
[英]How to iterate through a list of URLs for BeautifulSoup Web Scraping?
我的问题很简单:我正在尝试遍历 URL 列表并使用 Requests 和 BeautifulSoup 抓取每个 URL 的内容。 但是,看起来 for 循环似乎没有正确地将新 URL 分配给 requests 方法并返回第一个 URL 的内容,而不管循环当前处于哪个迭代。 如果你运行这个,你会看到“print(url)”返回正确的 URL,但“taglist”的内容总是来自 URL #1 的结果。 我会将我的代码粘贴在下面,以防你们中的任何人发现错误。 谢谢!
import requests
import os
import bs4
import pandas as pd
import numpy as np
urllist = ['https://www.stoneagetools.com/waterblast-tools-automated-equipment#exchanger','https://www.stoneagetools.com/waterblast-tools-automated-equipment#pipe','https://www.stoneagetools.com/waterblast-tools-automated-equipment#surface','https://www.stoneagetools.com/waterblast-tools-automated-equipment#tank','https://www.stoneagetools.com/waterblast-tools-automated-equipment#boiler','https://www.stoneagetools.com/waterblast-tools-automated-equipment#tools','https://www.stoneagetools.com/waterblast-tools-automated-equipment#swivels','https://www.stoneagetools.com/waterblast-tools-automated-equipment#accessories']
def Get_Names(urllist):
endlist = []
for url in urllist:
templist = []
print(url)
response = requests.get(url)
html = response.content
soup = bs4.BeautifulSoup(html, 'lxml')
taglist = soup.find_all('h3')
del taglist[0]
for tag in taglist:
tag_str = str(tag)
clean1 = tag_str.replace('<h3>','')
clean2 = clean1.replace('</h3>','')
templist.append(clean2)
endlist.append(templist)
return endlist
对于您想要做的事情,您的代码没有错误。 您每次抓取的网页都是相同的。 您所做的是转到该页面上的不同部分,这就是每个链接中的#
所做的。
所有产品都已经在页面初始页面上。 要将所有产品及其部分作为 pandas DataFrame,您可以使用下一个示例:
import requests
import pandas as pd
from bs4 import BeautifulSoup
url = "https://www.stoneagetools.com/waterblast-tools-automated-equipment"
soup = BeautifulSoup(requests.get(url).content, "html.parser")
all_data = []
for div in soup.select("section.directory > div"):
section = div.find_previous("h2").get_text(strip=True)
name1 = div.h3.get_text(strip=True)
name2 = div.h5.get_text(strip=True)
all_data.append([section, name1, name2])
df = pd.DataFrame(all_data, columns=["Section", "Name1", "Name2"])
print(df.head(15).to_markdown(index=False))
印刷:
部分 | 名称1 | 名称2 |
---|---|---|
交换器清洁 | AutoPack 3L 哨兵 | 智能自动化设备套件 |
交换器清洁 | 自动包装 3L | 自动化设备套件 |
交换器清洁 | 自动包装 2L | 自动化设备套件 |
交换器清洁 | AutoPack 指南针 | 自动化设备套件 |
交换器清洁 | 自动包装专业版 | 自动化设备套件 |
交换器清洁 | 自动箱 2L | 双弹性采血系统 |
交换器清洁 | 自动箱 3L | 三重柔性采血系统 |
交换器清洁 | ProDrive | AutoBox ABX-PRO 软管喂料拖拉机 |
交换器清洁 | 捆绑冲击波 | 壳程换热器清洗 |
交换器清洁 | 罗盘 | ABX-PRO 径向分度器 |
交换器清洁 | 密闭空间套件 | 罗盘径向分度器 |
交换器清洁 | 鳍扇配件 | 对于 AutoBox 系统 |
交换器清洁 | 软管管理系统 | 用于 AutoBox 软管拖拉机 |
交换器清洁 | 轻型定位器 | 对于 AutoBox 系统 |
交换器清洁 | 刚性喷枪机 | 用于交换管 |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.