簡體   English   中英

使用Python和BS4循環抓取多個頁面

[英]Loop Scraping Multiple Pages Using Python and BS4

我是一名學生記者,是python的新手。 我一直在嘗試找出如何使用for循環在我大學的日常犯罪日志的所有當前頁面上抓取每個犯罪日志。 但是,它只是抓取第一頁。 我一直在查看其他人的代碼和問題,無法真正弄清我所缺少的內容。 任何幫助表示贊賞,謝謝。

 import urllib.request import requests import csv import bs4 import numpy as np import pandas as pd from pandas import DataFrame for num in range(27): #Number of pagers plus url = ("http://police.psu.edu/daily-crime-log?field_reported_value[value]&page=0".format(num)) r = requests.get(url) source = urllib.request.urlopen(url).read() bs_tree = bs4.BeautifulSoup(source, "lxml") incident_nums = bs_tree.findAll("div", class_="views-field views-field-title") occurred = bs_tree.findAll("div", class_="views-field views-field-field-occurred") reported = bs_tree.findAll("div", class_="views-field views-field-field-reported") incidents = bs_tree.findAll("div", class_="views-field views-field-field-nature-of-incident") offenses = bs_tree.findAll("div", class_="views-field views-field-field-offenses") locations = bs_tree.findAll("div", class_="views-field views-field-field-location") dispositions = bs_tree.findAll("div", class_="views-field views-field-field-case-disposition") allCrimes = pd.DataFrame(columns = ['Incident#', 'Occurred', 'reported', 'nature of incident', 'offenses', 'location', 'disposition']) total = len(incident_nums) count = 0 while (count<total): incNum = incident_nums[count].find("span", class_="field-content").get_text() occr = occurred[count].find("span", class_="field-content").get_text() repo = reported[count].find("span", class_="field-content").get_text() incNat = incidents[count].find("span", class_="field-content").get_text() offe = offenses[count].find("span", class_="field-content").get_text() loca = locations[count].find("span", class_="field-content").get_text() disp = dispositions[count].find("span", class_="field-content").get_text() allCrimes.loc[count] =[incNum, occr, repo, incNat, offe, loca, disp] count +=1 

遵循別人的例子不一定是壞習慣,但是您需要在添加內容時檢查它們是否起作用,至少直到您獲得信心為止。

例如,如果您嘗試自己運行此for循環...

>>> for num in ('29'):
...     num
...     
'2'
'9'

您會看到Python在num中用'2'代替了'9'。 不是您想要的。

如果我跟隨您的線索,檢查了該站點,就會發現第0到26頁存在。 我可以for num in range(27)編碼。 可以理解為零初始值,循環比我給出的值小一。 在請求URL的語句中,您需要將此整數值轉換為字符串值(格式)。

您多次經歷了循環而沒有保留任何內容! 如果您希望在循環過程中執行其他語句,則需要縮進它們(或者在提交代碼時發生這種情況)。

此后,我不清楚您在做什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM