我写了下面的代码,它会导致错误:
price = item.find('span', "sx-zero-spacing'").text
,此行会导致错误:AttributeError: 'NoneType' object has no attribute 'text'
csvfile = open('scraper_data_csv', 'a') PermissionError: [Errno 13] Permission denied: 'scraper_data_csv'
请提供任何帮助或建议!谢谢!
from bs4 import BeautifulSoup
import requests
import csv
url = "https://www.amazon.com/s/?field-keywords=horse+head+mask"
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get(url, headers = headers)
soup = BeautifulSoup(response.text, "html.parser")
items = soup.find_all("li", "s-result-item")
csvfile = open('scraper_data.csv', 'a')
writer = csv.writer(csvfile)
for item in items:
name = item.find('h2').text
price = item.find('span', "sx-zero-spacing'").text
writer.writerow([name, price])
答案 0 :(得分:0)
而不是with open
,请尝试try
,它会在块结束时自动关闭文件。另外,使用except
/ sx-zero-spacing
来捕获没有from bs4 import BeautifulSoup
import requests
import csv
url = 'https://www.amazon.com/s/?field-keywords=horse+head+mask'
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
items = soup.find_all('li', 's-result-item')
with open('scraper_data.csv', 'w') as csvfile:
writer = csv.writer(csvfile)
for item in items:
try:
name = item.find('h2').text
price = item.find('span', 'sx-zero-spacing').text
except AttributeError:
continue
writer.writerow([name, price])
的商品。
Students Name: Grade:
1. Ben 1
2. Cathy 1
3. Tom 1
4. Mark 1
5. Lisa 1
6. Bernard 1
7. John 2
8. Macy 2
9. Rose 2
10. Maynard 2
11. Bill 2
12. Sherlock 2