python - 使用 BeautifulSoup 在多个页面上编写循环

标签 python loops beautifulsoup mechanize bs4

我试图从这里的县搜索工具中抓取几页结果:http://www2.tceq.texas.gov/oce/waci/index.cfm?fuseaction=home.main

但我似乎无法弄清楚如何迭代不仅仅是第一页。

import csv
from mechanize import Browser
from bs4 import BeautifulSoup

url = 'http://www2.tceq.texas.gov/oce/waci/index.cfm?fuseaction=home.main'

br = Browser()
br.set_handle_robots(False)
br.open(url)

br.select_form("county_search_form")

br.form['county_select'] = ['111111111111180']
br.form['start_date_month'] = ['1']
br.form['start_date_day'] = ['1']
br.form['start_date_year'] = ['2014']

br.submit()

soup = BeautifulSoup(br.response())

complaints = soup.find('table', class_='waciList')

output = []

import requests
for i in xrange(1,8):
    page = requests.get("http://www2.tceq.texas.gov/oce/waci/index.cfm?fuseaction=home.search&pageNumber={}".format(i))
    if not page.ok:
        continue
    soup = BeautifulSoup(requests.text)

    for tr in complaints.findAll('tr'):
        print tr
        output_row = []
        for td in tr.findAll('td'):
            output_row.append(td.text.strip())

        output.append(output_row)

br.open(url)
print 'page 2'
complaints = soup.find('table', class_='waciList')

for tr in complaints.findAll('tr'):
    print tr

with open('out-tceq.csv', 'w') as csvfile:
    my_writer = csv.writer(csvfile, delimiter='|')
    my_writer.writerows(output)

我只得到输出 CSV 中第一页的结果。在查看了使用 bs4 的其他抓取示例后,我尝试添加导入请求循环,但收到错误消息“导入错误:没有名为请求的模块”。

关于我应该如何循环遍历所有八页结果以将它们放入 .csv 的任何想法?

最佳答案

你实际上并不需要 requests迭代分页搜索结果的模块,mechanize绰绰有余。这是使用 mechanize 的一种可能方法.

首先,从当前页面获取所有分页链接:

links = br.links(url_regex=r"fuseaction=home.search&pageNumber=")

然后遍历分页链接,打开每个链接并在每次迭代时从每个页面收集有用的信息:
for link in links:
    #open link url:
    br.follow_link(link)

    #print url of current page, just to make sure we are on the expected page:
    print(br.geturl())

    #create soup from HTML of previously opened link:
    soup = BeautifulSoup(br.response())

    #TODO: gather information from current soup object here

关于python - 使用 BeautifulSoup 在多个页面上编写循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30068672/

相关文章:

javascript - 带变量的数组中的多个提示,可能吗?

loops - 你如何在 Rust 中创建一个范围?

Python - 副作用/纯度分析工具?

python - 从 Pandas 系列中删除 NaN

Python 对替换文本中的十六进制转义的支持

javascript - 无法将键设置为 for 循环内的对象

python - 在 python 中抓取表

python - BeautifulSoup 循环不迭代其他节点

python - 使用 BeautifulSoup 直接从 HTML 中提取数据

python - numpy 和 ctypes : dealing with views