Python/beautifulSoup/scrapingに関する質問と回答はありがたいですが、このシナリオについてはあまり見ていません。現在、私のコードは検索結果のページをループしてcsv docを作成することができますが、個々のテーブルについては、次の結果ページに移動する前に最初の行のみをコピーします。例えば、this page。現在、私の出力は次のようになります。Webスクレイピング:結果ページとテーブル行をループする
Brian Benoit,25-Jun-16,Conservative,12-May-16,25-Jun-16,Medicine Hat--Cardston--Warner,b'Medicine Hat--Cardston--Warner',Nikolai Punko
それは、代わりに次のようになります(。テーブル内のすべての行のためなど)
Brian Benoit,25-Jun-16,Conservative,12-May-16,25-Jun-16,Medicine Hat--Cardston--Warner,b'Medicine Hat--Cardston--Warner',Nikolai Punko
Paul Hinman,25-Jun-16,Conservative,12-May-16,25-Jun-16,Medicine Hat--Cardston--Warner,b'Welling, Alberta',Robert B. Barfuss
Michael Jones,25-Jun-16,Conservative,12-May-16,25-Jun-16,Medicine Hat--Cardston--Warner,b'Raymond, Alberta',Dawn M. Hamon
私の質問があります:どのようにループして、各行をこすって次の結果ページに進むのですか?ありがとう。あなたの問題へ
from bs4 import BeautifulSoup
import requests
import re
import csv
url = "http://www.elections.ca/WPAPPS/WPR/EN/NC?province=-1&distyear=2013&district=-1&party=-1&pageno={}&totalpages=55&totalcount=1368&secondaryaction=prev25"
with open('scrapeAllRows.csv', 'w', newline='') as f_output:
csv_output = csv.writer(f_output)
for i in range(1, 56):
print(i)
r = requests.get(url.format(i))
data = r.text
soup = BeautifulSoup(data, "html.parser")
links = []
for link in soup.find_all('a', href=re.compile('selectedid=')):
links.append("http://www.elections.ca" + link.get('href'))
for link in links:
r = requests.get(link)
data = r.text
cat = BeautifulSoup(data, "html.parser")
header = cat.find_all('span')
tables = cat.find_all("table")[0].find_all("td")
row = [
#"name":
re.sub("[\n\r/]", "", cat.find_all("table")[0].find_all("td", headers="name/1")[0].contents[0]).strip(),
#"date":
header[2].contents[0],
#"party":
re.sub("[\n\r/]", "", cat.find("legend").contents[2]).strip(),
#"start_date":
header[3].contents[0],
#"end_date":
header[5].contents[0],
#"electoral district":
re.sub("[\n\r/]", "", cat.find_all('div', class_="group")[2].contents[2]).strip(),
#"registered association":
re.sub("[\n\r/]", "", cat.find_all('div', class_="group")[2].contents[2]).strip().encode('latin-1'),
#"elected":
re.sub("[\n\r/]", "", cat.find_all("table")[0].find_all("td", headers="elected/1")[0].contents[0]).strip(),
#"address":
re.sub("[\n\r/]", "", cat.find_all("table")[0].find_all("td", headers="address/1")[0].contents[0]).strip(),
#"financial_agent":
re.sub("[\n\r/]", "", cat.find_all("table")[0].find_all("td", headers="fa/1")[0].contents[0]).strip()]
csv_output.writerow(row)
ありがとうございました!私はちょうどコードを実行し、それはまだ出力csvの各テーブルから1行だけを記録します - この場合、最後の行のように見えます。おそらく、それ自体が上書きされています。解析機能を拡張できますか? – HowenWilson
遅れて申し訳ありません。私は 'csv_output.writerow(行)'が正しく字下げされていないことに気付きました( "貼り付け"の問題かもしれません)。それはfor tr in trs [1:] 'ループの内側になければなりません。私はコードを修正した。 –