[英]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(或.contents)屬性訪問每個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.