【发布时间】:2020-08-16 15:41:59
【问题描述】:
我对 Python 和一般编码非常陌生。我在 YouTube 上关注关于网页抓取的视频教程,但在尝试运行我的代码时遇到了问题。
我想做什么:
- 我正在尝试编写查询以从中提取所有首页交易 一个网站 (CigarMonster.com) 并拉取 5 个属性 (Cigar 描述、尺寸/数量描述、原价、销售价格和 百分比折扣)来自页面上的每个列表。我想捕捉 CSV 文件中的内容。
我尝试过的:
- 我一直在 Anaconda 中测试代码,每个单独的属性都获取了正确的 text/html。
- 我无法运行整个脚本。我收到错误消息,但不确定发生了什么。
下面是脚本:
from urllib.request import Request, urlopen
from bs4 import BeautifulSoup as soup
#opens up connection and grabs the webpage
url = 'https://www.cigarmonster.com/'
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
web_byte = urlopen(req).read()
webpage = web_byte.decode('utf-8')
#parses html
page_soup = soup(webpage, "html.parser")
# grabs each of the products
containers = page_soup.findAll("div",{"class":"quickview-pop launchModal"})
filename = "cigar_list.csv"
f = open(filename, "w")
headers = "cigar_brand,product_size,famous_price, monster_price, percent_off"
f.write(headers)
for container in containers:
try:
cigar_brand = container.find("div",{"class":"item-grid-product-title"}).text
except Exception as e:
cigar_brand = "NA"
else:
pass
finally:
pass
size_container = container.findAll("span", {"class":"product-subtitle"})
product_size = size_container[0].text
famous_price_container = container.findAll("div",{"class":"col-xs-12 item-grid-product-fss-price"})
famous_price = famous_price_container[0].text
monster_price_container = container.findAll("div",{"class":"col-xs-12 item-grid-product-monster-price"})
monster_price = monster_price_container[0].text
percent_off_container = container.findAll("div",{"class":"col-xs-12 item-grid-product-fss-pct"})
percent_off = percent_off_container[0].text
#print("cigar_brand: " + cigar_brand)
#print("product_size: " + product_size)
#print("famous_price: " + famous_price)
#print("monster_price: " + monster_price)
#print("percent_off: " + percent_off)
f.write(cigar_brand + "," + product_size + "," + famous_price + "," + monster_price + "," + percent_off + "\n")
f.close()
运行脚本时出现以下错误:
Traceback (most recent call last):
File "cigar_monster_scrape.py", line 8, in <module>
uClient = urlopen(uReq).read()
File "C:\Users\nmbuc\anaconda3\lib\urllib\request.py", line 222, in urlopen
return opener.open(url, data, timeout)
File "C:\Users\nmbuc\anaconda3\lib\urllib\request.py", line 525, in open
response = self._open(req, data)
File "C:\Users\nmbuc\anaconda3\lib\urllib\request.py", line 547, in _open
return self._call_chain(self.handle_open, 'unknown',
File "C:\Users\nmbuc\anaconda3\lib\urllib\request.py", line 502, in _call_chain
result = func(*args)
File "C:\Users\nmbuc\anaconda3\lib\urllib\request.py", line 1421, in unknown_open
raise URLError('unknown url type: %s' % type)
urllib.error.URLError: <urlopen error unknown url type: https>
一开始我也遇到了相当多的缩进错误。
【问题讨论】:
-
您应该在帖子底部包含您遇到的错误
-
如果您尝试将第 8 行的
req变量替换为url会怎样 -
不知道是不是和我的安装有关。有人有我可以尝试的示例汤代码 .py 文件吗?我尝试运行人们说可以运行的代码,但仍然遇到类似问题。
标签: python web-scraping beautifulsoup