python - 如何限制在for循环中填充数据框的行数
问题描述
我编写了以下从网站上抓取多个页面的函数。我只想得到前 20 页左右。如何限制填写数据框的行数:
def scrape_page(poi,page_name):
base_url="https://www.fake_website.org/"
report_url=(base_url+poi)
page=urlopen(report_url)
experiences=BeautifulSoup(page,"html.parser")
empty_list=[]
for link in experiences.findAll('a', attrs={'href': re.compile(page_name+".shtml$")}):
url=urljoin(base_url, link.get("href"))
subpage=urlopen(url)
expages=BeautifulSoup(subpage, "html.parser")
for report in expages.findAll('a', attrs={'href': re.compile("^/experiences/exp")}):
url=urljoin(base_url, report.get("href"))
reporturlopen=urlopen(url)
reporturl=BeautifulSoup(reporturlopen, "html.parser")
book_title= reporturl.findAll("div",attrs={'class':'title'})
for i in book_title:
title=i.get_text()
book_genre= reporturl.findAll("div",attrs={'class':'genre'})
for i in book_genre:
genre=i.get_text()
book_author= reporturl.findAll("div",attrs={'class':'author'})
for i in book_author:
author=i.get_text()
author = re.sub("by", "",author)
empty_list.append({'title':title,'genre':genre,'author':author})
setattr(sys.modules[__name__], '{}_df'.format(poi+"_"+page_name), empty_list)
解决方案
例如,您可以添加一个 while 循环:
i = 0
while i < 20:
< insert your code >
i += 1
推荐阅读
- web-component - “slotchange”事件不会在 iOS 11 上触发
- html - 为什么额外的垂直滚动条出现在 mat-tab-body-content 中,我需要使用 overflow-auto height 100%
- python - 如何在使用 pdfkit.from_string() 生成的 pdf 中添加换行符?
- java - 我如何模拟方法,从另一种方法调用一个方法?
- json - 需要通过 JSON Patch 在 JSON 中添加列表
- python - CSS Style 可以像 wxpython 框架那样实现 gui python 应用吗
- jquery - 如何使用jquery数据表对最后一项显示第一页最后一项的顺序进行排序?
- c - (PSET5 cs50)卸载链表数组时出现段错误
- android - 材质 TexInputLayout 改变颜色
- php - 如何将 .htacess(apache) 转换为 Nginx