2017-09-14 15 views
0

私はウェブサイトを削り取ろうとしていますが、このコードを実行するとデータの半分(批評家のデータを含む)しか印刷されません。ここに私のスクリプトは次のとおりです。BeautifulSoupはすべてのデータを削っていません

from bs4 import BeautifulSoup 
from urllib.request import urlopen 

inputfile = "Chicago.csv" 
f = open(inputfile, "w") 
Headers = "Name, Link\n" 
f.write(Headers) 

url = "https://www.chicagoreader.com/chicago/best-of-chicago-2011-food-drink/BestOf?oid=4106228" 
html = urlopen(url) 
soup = BeautifulSoup(html, "html.parser") 

page_details = soup.find("dl", {"class":"boccat"}) 
Readers = page_details.find_all("a") 

for i in Readers: 
    poll = i.contents[0] 
    link = i['href'] 
    print(poll) 
    print(link) 
    f.write("{}".format(poll) + ",https://www.chicagoreader.com{}".format(link)+ "\n") 
f.close() 
  1. は私のスクリプトスタイル間違ってますか?
  2. コードを短くするにはどうすればよいですか?
  3. find_allfindを使用すると、属性エラーが発生します。私は書類を読むが、理解していない。

答えて

0

コードを短くするには、リクエストライブラリに切り替えます。使いやすく、正確です。さらに短くしたいなら、cssselectを使うことができます。

findはコンテナを選択し、find_allはforループ内のそのコンテナの個々の項目を選択します。

from bs4 import BeautifulSoup 
import csv ; import requests 

outfile = open("chicagoreader.csv","w",newline='') 
writer = csv.writer(outfile) 
writer.writerow(["Name","Link"]) 

base = "https://www.chicagoreader.com" 

response = requests.get("https://www.chicagoreader.com/chicago/best-of-chicago-2011-food-drink/BestOf?oid=4106228") 
soup = BeautifulSoup(response.text, "lxml") 
for item in soup.select(".boccat dd a"): 
    writer.writerow([item.text,base + item.get('href')]) 
    print(item.text,base + item.get('href')) 

または検索とfind_allと::ここに完成したコードがある

from bs4 import BeautifulSoup 
import requests 

base = "https://www.chicagoreader.com" 

response = requests.get("https://www.chicagoreader.com/chicago/best-of-chicago-2011-food-drink/BestOf?oid=4106228") 
soup = BeautifulSoup(response.text, "lxml") 
for items in soup.find("dl",{"class":"boccat"}).find_all("dd"): 
    item = items.find_all("a")[0] 
    print(item.text, base + item.get("href")) 
+0

シャヒンこんにちは、あなたはfind_allのと見つけるの短い例を提供してくださいすることができますか..? –

+0

@ Mr.Bones、私は既にfindとfind_allの例を挙げました。上記をご覧ください。 – SIM