繁体   English   中英

使用Python自动执行网络搜索

[英]Using Python to Automate Web Searches

我想通过访问一个网站并反复搜索来使自己的工作自动化。 特别是,我一直去本网站 ,向下滚动到底部附近,单击“即将到来”选项卡,并搜索各个城市。

我是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,尽管我不确定该如何处理,但这听起来似乎是一个小小的胜利。

帮助将不胜感激,谢谢。

您有两个问题合而为一,所以这里有部分答案可以帮助您开始。 第一个任务涉及HTML解析,因此让我们使用python库:requests和beautifulsoup4(如果尚未安装,请pip安装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方法来提取类为'upcoming_performance'的'tr'元素。 行中的单个元素如下所示:

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- *属性可通过字典键查找获得。

可以使用.children(或.c​​ontents)属性访问每个tr元素内的'td'元素。

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:浮动

lng:浮动

邮政编码:str

performance_city-state:str

performance_organization:str

等等

HTML提取完成。 下一步是使用Mapping API服务,该服务会比较您期望的位置与表演中经度/纬度值之间的距离。 例如,您可以选择使用Google Maps地理编码API。 有很多关于SO的已回答问题可以指导您。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM