【发布时间】:2014-11-15 06:10:22
【问题描述】:
我正在尝试从[www.quicktransportsolutions.com][1] 中提取公司名称、地址和邮政编码。我编写了以下代码来潦草网站并返回我需要的信息。
import requests
from bs4 import BeautifulSoup
def trade_spider(max_pages):
page = 1
while page <= max_pages:
url = 'http://www.quicktransportsolutions.com/carrier/missouri/adrian.php'
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text)
for link in soup.findAll('div', {'class': 'well well-sm'}):
title = link.string
print(link)
trade_spider(1)
运行代码后,我看到了我想要的信息,但我很困惑如何在没有所有不相关信息的情况下打印它。
上方
print(link)
我认为我可以让 link.string 提取公司名称,但失败了。有什么建议?
输出:
div class="well well-sm">
<b>2 OLD BOYS TRUCKING LLC</b><br><a href="/truckingcompany/missouri/2-old-boys-trucking-usdot-2474795.php" itemprop="url" target="_blank" title="Missouri Trucking Company 2 OLD BOYS TRUCKING ADRIAN"><u><span itemprop="name"><b>2 OLD BOYS TRUCKING</b></span></u></a><br> <span itemprop="address" itemscope="" itemtype="http://schema.org/PostalAddress"><a href="http://maps.google.com/maps?q=227+E+2ND,ADRIAN,MO+64720&ie=UTF8&z=8&iwloc=addr" target="_blank"><span itemprop="streetAddress">227 E 2ND</span></a>
<br>
<span itemprop="addressLocality">Adrian</span>, <span itemprop="addressRegion">MO</span> <span itemprop="postalCode">64720</span></br></span><br>
Trucks: 2 Drivers: 2<br>
<abbr class="initialism" title="Unique Number to identify Companies operating commercial vehicles to transport passengers or haul cargo in interstate commerce">USDOT</abbr> 2474795 <br><span class="glyphicon glyphicon-phone"></span><b itemprop="telephone"> 417-955-0651</b>
<br><a href="/inspectionreports/2-old-boys-trucking-usdot-2474795.php" itemprop="url" target="_blank" title="Trucking Company 2 OLD BOYS TRUCKING Inspection Reports">
大家,
感谢到目前为止的帮助...我正在尝试为我的小爬虫添加一个额外的功能。我写了以下代码:
def Crawl_State_Page(max_pages):
url = 'http://www.quicktransportsolutions.com/carrier/alabama/trucking-companies.php'
while i <= len(url):
response = requests.get(url)
soup = BeautifulSoup(response.content)
table = soup.find("table", {"class" : "table table-condensed table-striped table-hover table-bordered"})
for link in table.find_all(href=True):
print link['href']
Output:
abbeville.php
adamsville.php
addison.php
adger.php
akron.php
alabaster.php
alberta.php
albertville.php
alexander-city.php
alexandria.php
aliceville.php
alpine.php
... # goes all the way to Z I cut the output short for spacing..
我在这里尝试完成的是使用 city.php 提取所有 href 并将其写入文件。 .. 但是现在,我陷入了一个无限循环,它不断循环通过 URL。关于如何增加它的任何提示?我的最终目标是创建另一个函数,该函数通过 www.site.com/state/city.php 反馈到我的 trade_spider,然后循环遍历所有 50 个日期...
while i < len(states,cities):
url = "http://www.quicktransportsolutions.com/carrier" + states + cities[i] +"
然后这将循环到我的 trade_spider 函数中,提取我需要的所有信息。
但是,在我进入那部分之前,我需要一些帮助来摆脱我的无限循环。有什么建议?或者我会遇到的可预见的问题?
我尝试创建一个爬虫,它会循环遍历页面上的每个链接,然后如果它在页面上找到 trade_spider 可以爬取的内容,它会将其写入文件......但是,这有点过时了我的技能,现在。所以,我正在尝试这种方法。
【问题讨论】:
标签: python python-2.7 html-parsing beautifulsoup scraper