繁体   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