python - 在python中使用beautifulsoup提取表数据时出现问题
问题描述
下面的代码以表格的形式为我提供了所需的产品数据。它适用于大多数链接,但在某些链接中会停止,给出错误NoneType
对象find_all
在table.find_all('tr)
.
我相信这是因为某些产品中不存在表,所以我尝试在表的存在上创建一个 if 条件,但这似乎也无济于事。我应该在下面的代码中进行哪些更改?
import requests, json, time
from bs4 import BeautifulSoup
import pandas as pd
url = "https://www.1800wheelchair.com/category/toilet-accessories/?p="
headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0'}
data = []
for i in range(1,3):
print(i)
res = requests.get(url + str(i), headers=headers)
soup = BeautifulSoup(res.text, "html.parser")
p_links = [i["data-link"] for i in soup.find("ul", {"id":"products-list"}).find_all("li",class_=["openlink","item"])]
for prod_url in p_links:
print(prod_url)
temp = {"Product URL": prod_url}
prod_res = requests.get(prod_url, headers = headers)
prod_soup = BeautifulSoup(prod_res.text, "html.parser")
for p in prod_soup.find("div", class_="basic-information").find_all("p"):
if "item" in p.text.lower(): temp["item number"] = p.find("span").text.strip()
elif "brand" in p.text.lower(): temp["manufacturer"] = p.find("span").text.strip()
elif "sku" in p.text.lower(): temp["sku"] = p.find("span").text.strip()
table = prod_soup.find("table",{"class":"specifications"})
for tr in table.find_all("tr"):
temp[tr.find("td", {"class":"tdLabel"}).text.strip()] = tr.find("td", {"class":"tdValue"}).text.strip()
data.append(temp)
pd.DataFrame(data).to_csv("toilet-acc.csv", index=False)
解决方案
您可以使用Try
和Except
(文档):
try:
for tr in table.find_all("tr"):
temp[tr.find("td", {"class":"tdLabel"}).text.strip()] = tr.find("td", {"class":"tdValue"}).text.strip()
except:
pass
推荐阅读
- c# - PredicateBuilder 不适用于 Where 子句
- laravel - 如何使用 Laravel Eloquent updateOrCreate() 增加列?
- c++ - DirectX:即使我的系统表示支持,也无法创建 directx11 设备
- pandas - 如何利用DataFrame的优势扩展输入
- python - 为什么当我将代码放入服务器时,translator.detect(..).lang 给了我异常,而它在我的本地主机上运行良好
- .net - 使用 xml 阅读器捕获文件中的元素位置。抵消问题
- python - Wagtail:Elasticsearch 不会在短字段上提升匹配
- c++ - 为大型对象(超过 30 个字段)覆盖 istream 的最佳方法是什么?
- vue.js - 如何在放大确认注册 Vue 组件中设置标题文本而不删除默认行为?
- git - git:并行查看特定提交的源代码