2

我正在尝试从县搜索工具中抓取几页结果: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 的其他抓取示例后,我尝试添加导入请求循环,但收到错误消息“ImportError:没有名为请求的模块。”

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

4

1 回答 1

0

您实际上不需要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
于 2015-05-07T04:34:28.353 回答