使用BeautifulSoup

时间:2015-05-06 05:59:34

标签: 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查看其他刮擦示例后尝试添加导入请求循环,但收到错误消息“ImportError:No module named requests。”

有关如何循环遍历所有八页结果以使其进入.csv的任何想法?

1 个答案:

答案 0 :(得分: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
相关问题