Python使用Beautiful Soup的网页抓取程序出错
我已经根据在线教程编写了一些网页抓取代码,但遇到了一个错误。我的代码几乎与网上的内容完全匹配,但似乎仍有错误。有人能帮忙吗。根据错误类型,它似乎与文件名和路径有关。我在那里尝试了各种组合,但仍然有一个错误 我在下面复制了我的代码Python使用Beautiful Soup的网页抓取程序出错,python,beautifulsoup,Python,Beautifulsoup,我已经根据在线教程编写了一些网页抓取代码,但遇到了一个错误。我的代码几乎与网上的内容完全匹配,但似乎仍有错误。有人能帮忙吗。根据错误类型,它似乎与文件名和路径有关。我在那里尝试了各种组合,但仍然有一个错误 我在下面复制了我的代码 from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup my_url = 'https://www.newegg.com/Video-Cards-Video-De
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
my_url = 'https://www.newegg.com/Video-Cards-Video-Devices/Category/ID-38?Tpk=graphics%20cards'
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()
page_soup = soup(page_html, "html.parser")
containers = page_soup.finaAll("div", {"class":"item-container"})
filename = "C:\\Users\\_Alekhine_\\Python\\products.csv"
f = open(filename, "w")
headers = "brand, product_name, shipping\n"
f.write(" ")
for container in containers:
brand = container.div.div.a.img["title"]
title_container = container.findAll("a", {"class": "item-title"})
product_name = title_container[0].text
shipping_container = container.findAll("li", {"class": "price-ship"})
shipping = shipping_container[0].text.strip()
print("brand: " + brand)
print("product_name: " + product_name)
print("shipping: " + shipping)
f.write(brand + "" + product_name.replace(",", "") + "" + shipping + "\n")
f.close()
由于您没有发布错误,我可以根据您的错误描述假设您在第14行中指定的路径不存在<如果文件路径不存在,即使在写入模式下,代码>打开也会失败。首先尝试创建目录
C:\Users\\u Alekhine\u\Python
您可以在Python(3.2+)中执行此操作:
顺便说一句,您的代码示例中也有一个输入错误(第12行应该是
findAll
而不是finaAll
),但我假设这不是您描述的错误。您遇到了什么错误?你不觉得这很重要吗?谢谢你的回复。C驱动器中的路径确实存在。我收到的错误消息是-TypeError:“NoneType”对象不可调用。代码现在正在创建一个CSV文件。再次感谢。
import os
os.makedirs(path, exist_ok=True)