我是初學者,我正在學習BeautifulSoup,想從網站獲取資訊,但是輸出沒有寫任何資訊,我不知道我在哪里做錯了,天哪,幫幫我
這是我的代碼
from selenium import webdriver
from bs4 import BeautifulSoup
import pandas as pd
driver = webdriver.Chrome("C:\\chromedriver\\chromedriver.exe")
products=[] #store name of the product
prices=[] #store price of the product
ratings=[] #store rating of the product
driver.get("http://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html")
content = driver.page_source
soup = BeautifulSoup(content,features="html.parser")
for a in soup.findAll('a',href=True, attrs={'container-fluid page'}):
name=a.find('div', attrs={'class':'col-sm-6 product_main'})
price=a.find('div', attrs={'class':'col-sm-6 product_main'})
rating=a.find('div', attrs={'class':'star-rating Three'})
products.append(name.text)
prices.append(price.text)
ratings.append(rating.text)
df = pd.DataFrame({'Product Name': products, 'Price': prices, 'Rating': ratings})
df.to_csv('D:\\products.csv', index=False, encoding='utf-8')
它沒有報告任何錯誤,我只是得到一個沒有資訊的 csv 檔案。
Product Name,Price,Rating
uj5u.com熱心網友回復:
注意 您的代碼中有一些內容,我建議保持簡單。您的策略應該是選擇id, tag, class- 此順序從靜態到更動態的提供資訊。在新代碼中使用find_all()而不是舊語法findAll()
主要問題是您的選擇soup.findAll('a',href=True, attrs={'container-fluid page'})不會找到任何東西,因此結果為空。事實上,這個頁面只有一個產品,它不需要所有這些串列。
...
soup = BeautifulSoup(content,"html.parser")
df = pd.DataFrame([{
'Product Name': soup.h1.text,
'Price': soup.find('p',{"class": "price_color"}).text,
'Rating': soup.find('p',{"class": "star-rating"})['class'][-1].lower()}])
...
例子
沒必要用selenium,也簡單看一下requests——從煮你soup的程序幾乎是一樣的:
import requests
from bs4 import BeautifulSoup
URL = 'http://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html'
content = requests.get(URL).content
soup = BeautifulSoup(content,"html.parser")
df = pd.DataFrame([{
'Product Name': soup.h1.text,
'Price': soup.find('p',{"class": "price_color"}).text,
'Rating': soup.find('p',{"class": "star-rating"})['class'][-1].lower()}])
df
#or to save as csv -> df.to_csv('D:\\products.csv', index=False, encoding='utf-8')
輸出
| 產品名稱 | 價錢 | 評分 |
|---|---|---|
| 閣樓上的一盞燈 | 51.77 英鎊 | 三 |
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/448275.html
