使用Python自动化Web搜索

时间:2015-08-02 20:38:48

标签: python web-crawler web-search

我想通过访问网站并反复搜索来自动化我一直在做的事情。特别是我去This Website,向下滚动靠近底部,点击“即将到来”标签,搜索各个城市。

我是Python的新手,我希望能够只输入要输入的城市列表进行搜索,并获得汇总所有搜索结果的输出。因此,例如,以下功能将是伟大的:

cities = ['NEW YORK, NY', 'LOS ANGELES, CA']
print getLocations(cities)

它会打印

Palm Canyon Theatre PALM SPRINGS, CA    01/22/2016  02/07/2016
...

依此类推,列出所有输入城市周围100英里范围内的所有搜索结果。

我已经尝试过查看Apache2的requests模块的文档,然后运行

r = requests.get('http://www.tamswitmark.com/shows/anything-goes-beaumont-1987/')
r.content

它打印了网页的所有HTML,这听起来像是一些小小的胜利,虽然我不知道如何处理它。

非常感谢帮助,谢谢。

1 个答案:

答案 0 :(得分:1)

你有两个问题合二为一,所以这里有一个部分答案让你开始。第一个任务涉及HTML解析,所以让我们使用python库:requests和beautifulsoup4(如果你还没有,请点击安装beautifulsoup4)。

import requests
from bs4 import BeautifulSoup

r = requests.get('http://www.tamswithmark.com/shows/anything-goes-beaumont-1987/')
soup = BeautifulSoup(r.content, 'html.parser')
rows = soup.findAll('tr', {"class": "upcoming_performance"})
汤是页面内容的可导航数据结构。我们在汤上使用findAll方法来提取' tr' class' coming_performance'。行中的单个元素如下所示:

print(rows[0])  # debug statement to examine the content
"""
<tr class="upcoming_performance" data-lat="47.6007" data-lng="-120.655" data-zip="98826">
<td class="table-margin"></td>
<td class="performance_organization">Leavenworth Summer Theater</td>
<td class="performance_city-state">LEAVENWORTH, WA</td>
<td class="performance_date-from">07/15/2015</td>
<td class="performance_date_to">08/28/2015</td>
<td class="table-margin"></td>
</tr>
"""

现在,让我们将这些行中的数据提取到我们自己的数据结构中。对于每一行,我们将为该性能创建一个字典。

每个tr元素的data- *属性可通过字典键查找获得。

&#39;&#39;可以使用.children(或.c​​ontents)属性访问每个tr元素中的元素。

performances = []  # list of dicts, one per performance
for tr in rows:
    # extract the data-* using dictionary key lookup on tr 
    p = dict(
        lat=float(tr['data-lat']),
        lng=float(tr['data-lng']),
        zipcode=tr['data-zip']
    )
    # extract the td children into a list called tds
    tds = [child for child in tr.children if child != "\n"]
    # the class of each td indicates what type of content it holds
    for td in tds:
       key = td['class'][0] # get first element of class list
       p[key] = td.string  # get the string inside the td tag
    # add to our list of performances
    performances.append(p)

此时,我们在表演中有一个词典列表。每个字典中的键是:

lat:float

lng:float

zipcode:str

performance_city-state:str

performance_organization:str

完成HTML提取。下一步是使用映射API服务,该服务将所需位置的距离与性能中的lat / lng值进行比较。例如,您可以选择使用Google Maps地理编码API。有很多现有的回答问题可以指导你。

相关问题