一般来说,我对Python和编码非常陌生。我在YouTube上观看了一个关于网络垃圾的视频教程,在运行代码时遇到了问题
我想做的是:
我所尝试的:
以下是脚本:
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>
一开始我也遇到了相当数量的缩进错误
更改代码下面的2行,然后就可以开始了。在下面的代码中,我使用了requests而不是urlibrest,一切都是一样的
相关问题 更多 >
编程相关推荐