Python 从Woeidlookup.com抓取WOEID

Python 从Woeidlookup.com抓取WOEID,python,python-3.x,Python,Python 3.x,我正试图做一个或多或少的天气检查。我正在刮雅虎这个,因为我不知道如何使用他们的API加上它似乎更有趣我。我已经很久没有使用Python3编写代码了。所有这些代码都是在RPI上完成的,它使用的Python3版本是3.4.2 我遇到的问题是如何获得WOEID号码。我想抓取Woeidlookup.com是一件很容易就能得到号码的事情。然而,在尝试了各种方法从网站上获取数据后,我来到了这里。我没有任何代码显示刮这个网站,好像它没有工作,我只是删除了它 我相信这里有人知道如何将所需的文本输入到 字段,然后

我正试图做一个或多或少的天气检查。我正在刮雅虎这个,因为我不知道如何使用他们的API加上它似乎更有趣我。我已经很久没有使用Python3编写代码了。所有这些代码都是在RPI上完成的,它使用的Python3版本是3.4.2

我遇到的问题是如何获得WOEID号码。我想抓取Woeidlookup.com是一件很容易就能得到号码的事情。然而,在尝试了各种方法从网站上获取数据后,我来到了这里。我没有任何代码显示刮这个网站,好像它没有工作,我只是删除了它

我相信这里有人知道如何将所需的文本输入到 字段,然后提交它。一旦它被提交,我必须刮掉显示在字段下面的表格,以获得WOEID编号

我已经完成了下面发布的雅虎天气刮。如果出于学习目的对代码提出任何批评,我们将不胜感激。在过去的几周里,我在这个网站上找到了大量有用的信息,这些知识大部分都用于这个项目。如果我决定稍后添加一个表而不是当前的print()设置,则将进行导入

导入请求
从bs4导入BeautifulSoup
作为pd进口熊猫
导入日期时间
baseurl=”https://www.yahoo.com/news/weather"
国家=输入(“国家:”)。替换(“,“-”)
状态=输入(“状态:”)。替换(“,“-”)
Town=输入(“Town:”)。替换(“,“-”)
WOEID=”“#这就是我需要弄清楚的
url='%(U)s/%(C)s/%(s)s/%(T)s-%(W)s“{'U”:基本url,“C”:国家,“s”:州,“T”:镇,“W”:世界}
now=datetime.datetime.now()
小时=0
分钟=现在
AMPM=“”
ToD=“”
page=请求.get(url)
代码=页面状态\代码
content=page.content
soup=BeautifulSoup(内容为“html.parser”)
天气=汤。查找(class=“天气”)
temp=soup.find(class_uz=“温度Fz(14px)Tsh($temperature text shadow)”)
风=天气。查找(id=“天气风”)
sunMoon=weather.find(id='weather-sun-moon')
详细信息=天气。查找(id=“天气详细信息”)
detail=details.find(class=“detail”)
开始=详细信息。查找所有(class=“Fl(开始)”)
end=详细信息。查找所有(class=“Fl(end)”)
desc=detail.find(class_uux=“描述Py(10px)Px(4px)Fz(1em)”)
dayNight=desc.find_all(class_uu=“day description My(10px)”)
windText=wind.find('span',{'data-reactid':'455'}).text
windSpeedDir=wind.find('p',{'data-reactid':'456'})。文本
baro=wind.find('span',{'data-reactid':'461')。文本
压力=风。查找('p',{'data-reactid':'462'})。文本
phase=sunMoon.find('div',{'data-reactid':'504'})。文本
dayDesc=temp.find(class_uux=“描述Va(m)Px(2px)Fz(1.3em)--sm Fz(1.6em)”)
currentTemp=temp.find('span',{'data-reactid':'37')。文本
degreeSymbol=temp.find('span',{'data-reactid':'38'})。文本
high=temp.find('span',{'data-reactid':'29'})。文本
low=temp.find('span',{'data-reactid':'33')。文本
city=weather.find(class=“city Fz(2em)--sm Fz(3.7em)--lg Fz(3.3em)Fw(n)M(0)Trsdu(.3s)桌面(1)智能手机(1)”)
国家=天气。查找(class_uz(1.2em)--sm Fz(2em)--lg Fz(1.5em)Fw(200)国家Trsdu(.3s)Lh(2.5)”)
dateTime=weather.find(class_ux=“Lts(1px)Fz(14px)Fs(i)Lh(2.5)Fw(300)Tsh($temperature text shadow)”)
尝试:
sunrise=sunMoon.find('span',{'data-reactid':'510')。文本
除:
sunrise=sunMoon.find('span',{'data-reactid':'515'})。文本
尝试:
sunset=sunMoon.find('span',{'data-reactid':'511'}).text
除:
sunset=sunMoon.find('span',{'data-reactid':'516'}).text
日出1=日出。分割(“”)
sunrise2=sunrise1[0]。拆分(“:”)
srHour=int(日出2[0])
srMinute=int(日出2[1])
sunset1=日落。分割(“”)
sunset2=sunset1[0]。拆分(“:”)
ssHour=int(太阳集2[0])
ssMinute=int(太阳集2[1])
如果now.hour>12:
小时=现在。小时-12
AMPM=“PM”
其他:
小时=现在。小时
AMPM=“AM”
如果now.hour>=srHour且now.hour<12:
ToD=“早上好”
如果now.hour>=12且now.hour-1212且now.hour-12>=ssHour:
ToD=“晚上”
打印('的城市的天气数据',city.get_text(),'的国家',country.get_text())
打印('Today is'、%02d“%(now.month)、'/'、%02d“%(now.day)、'/'、now.year)
打印('当前时间为',%02d'%(小时),“:”,%02d'%(现在.分钟),“:”,%02d'%(现在.秒),安培)
打印('现在是一个',dayDesc.get_text().lower(),ToD,'天空')
打印('当前为',当前温度,度数符号'F')
打印('今天的最高点是',最高点是',F.))
打印('今天的下限为',下限为'F'。)
打印(开始[0]。获取文本(),':',结束[0]。获取文本()
打印(开始[1]。获取文本(),':',结束[1]。获取文本()
打印(开始[2]。获取文本(),':',结束[2]。获取文本()
打印(开始[3]。获取文本(),':',结束[3]。获取文本()
打印(windText,“:”,windSpeedDir)
打印(气压,“:”,压力)
打印(“月亮相位:”,相位)
打印(“日出:”,日出)
打印(“日落:”,日落)
打印(dayNight[0]。获取文本()
打印(dayNight[1]。获取文本()

经过多次编码、搜索等。。我已经通过使用不同的网站获取WOEID和数据解决了问题。下面是我为学校的项目制作的完整脚本。我把它分为3个文件,在整个代码中都没有文档记录,但是应该很容易理解。希望这能帮助那些也在做类似事情的人,即使它的编码可能很糟糕

主脚本

import requests
from bs4 import BeautifulSoup
import pandas as pd
import datetime
import WeatherAppBS4_Woeid as woeid

baseurl = "https://www.yahoo.com/news/weather"
Country = woeid.Country.replace(" ", "-")
State = woeid.State.replace(" ", "-")
Town = woeid.Town.replace(" ", "-")
WOEID = woeid.WOEID

url = '%(U)s/%(C)s/%(S)s/%(T)s-%(W)s' % {'U': baseurl, "C": Country, "S": State, "T": Town, "W": WOEID}

now = datetime.datetime.now()
hour = 0
minute = now.minute
AMPM = ""
ToD = ""

page = requests.get(url)
code =  page.status_code
content = page.content
soup = BeautifulSoup(content, 'html.parser')
weather = soup.find(class_="weather")
temp = soup.find(class_="temperature Fz(14px) Tsh($temperature-text-shadow)")
wind = weather.find(id="weather-wind")
sunMoon = weather.find(id='weather-sun-moon')
details = weather.find(id="weather-detail")
detail = details.find(class_="detail")
start = detail.find_all(class_="Fl(start)")
end = detail.find_all(class_="Fl(end)")
desc = detail.find(class_="description Py(10px) Px(4px) Fz(1em)")
dayNight = desc.find_all(class_="day-description My(10px)")
windText = wind.find('span', {'data-reactid': '455'}).text
windSpeedDir = wind.find('p', {'data-reactid': '456'}).text
baro = wind.find('span', {'data-reactid': '461'}).text
pressure = wind.find('p', {'data-reactid': '462'}).text
phase = sunMoon.find('div', {'data-reactid': '504'}).text
dayDesc = temp.find(class_="description Va(m) Px(2px) Fz(1.3em)--sm Fz(1.6em)")
currentTemp = temp.find('span', {'data-reactid': '37'}).text
degreeSymbol = temp.find('span', {'data-reactid': '38'}).text
high = temp.find('span', {'data-reactid': '29'}).text
low = temp.find('span', {'data-reactid': '33'}).text
city = weather.find(class_="city Fz(2em)--sm Fz(3.7em)--lg Fz(3.3em) Fw(n) M(0) Trsdu(.3s) desktop_Lh(1) smartphone_Lh(1)")
country = weather.find(class_="Fz(1.2em)--sm Fz(2em)--lg Fz(1.5em) Fw(200) country Trsdu(.3s) Lh(2.5)")
dateTime = weather.find(class_="Lts(1px) Fz(14px) Fs(i) Lh(2.5) Fw(300) Tsh($temperature-text-shadow)")

try:
    sunrise = sunMoon.find('span', {'data-reactid': '510'}).text
except:
    sunrise = sunMoon.find('span', {'data-reactid': '515'}).text
try:
    sunset = sunMoon.find('span', {'data-reactid': '511'}).text
except:
    sunset = sunMoon.find('span', {'data-reactid': '516'}).text

sunrise1 = sunrise.split(" ")
sunrise2 = sunrise1[0].split(":")
srHour = int(sunrise2[0])
srMinute = int(sunrise2[1])
sunset1 = sunset.split(" ")
sunset2 = sunset1[0].split(":")
ssHour = int(sunset2[0])
ssMinute = int(sunset2[1])

if now.hour > 12:
    hour = now.hour - 12
    AMPM = "PM"
else:
    hour = now.hour
    AMPM = "AM"

if now.hour >= srHour and now.hour < 12:
    ToD = "morning"
if now.hour >= 12 and now.hour < ssHour:
    ToD = "afternoon"
if now.hour > 12 and now.hour >= ssHour:
    ToD = "night"

print('Weather data for the city of', city.get_text(), 'in the country of', country.get_text())
print('Today is', "%02d" % (now.month), '/', "%02d" % (now.day), '/', now.year)
print('The current time is', "%02d" % (hour), ":", "%02d" % (now.minute), ":", "%02d" % (now.second), AMPM)
print('Right now it is a', dayDesc.get_text().lower(), ToD, 'sky.')
print('It is currently', currentTemp, degreeSymbol, 'F.')
print('The high for today is', high, 'F.')
print('The low for today is', low, 'F.')
print(start[0].get_text(), ' : ', end[0].get_text())
print(start[1].get_text(), '   : ', end[1].get_text())
print(start[2].get_text(), ' : ', end[2].get_text())
print(start[3].get_text(), '   : ', end[3].get_text())
print(windText, "       : ", windSpeedDir)
print(baro, "  : ", pressure)
print("Moon Phase  : ", phase)
print("Sunrise     : ", sunrise)
print("Sunset      : ", sunset)
print(dayNight[0].get_text())
print(dayNight[1].get_text())
机械组脚本

import requests
import mechanicalsoup
import bs4 as BeautifulSoup

browserurl = "http://woeid.rosselliot.co.nz"
userInput = input('Town, state, country, address, zipcode or landmark : ').replace(',','%20').replace(' ','%20')
browser = mechanicalsoup.StatefulBrowser()

browser.open(browserurl)
browser.select_form('form[action="http://woeid.rosselliot.co.nz/lookup"]')
browser["place"] = userInput

browser.close()

baseurl = "http://woeid.rosselliot.co.nz/lookup"
url = '%(U)s/%(I)s' % {'U': baseurl, "I": userInput}

我看到这一点的方式是,我有两种方法来获得我想要的结果。1.使用某种python API插件单击网页上的ChangeLocation按钮,该按钮将显示我已经拥有的其余部分的代码。2.找出如何从我所说的仅基于邮政编码输入的网站中获取WOEID。最好是我想选择1的基础上,我已经看到了迄今为止试图与其他人互动
import requests
import bs4 as BeautifulSoup
import pandas as pd
import WeatherAppMECH as mech

page = requests.get(mech.url)
code =  page.status_code
content = page.content
soup = BeautifulSoup.BeautifulSoup(content, 'html.parser')
search = soup.find(id="content")
results = search.find('div', {'id': 'lookup_result'})

rows=list()
for tr in results.find('table', {'id':'woeid_results_table'}):
    for td in tr:
        rows.append(td.string)
resultList=rows[1:]

Town = resultList[0]
State = resultList[1]
Country = resultList[2]
WOEID = resultList[3]
import requests
import mechanicalsoup
import bs4 as BeautifulSoup

browserurl = "http://woeid.rosselliot.co.nz"
userInput = input('Town, state, country, address, zipcode or landmark : ').replace(',','%20').replace(' ','%20')
browser = mechanicalsoup.StatefulBrowser()

browser.open(browserurl)
browser.select_form('form[action="http://woeid.rosselliot.co.nz/lookup"]')
browser["place"] = userInput

browser.close()

baseurl = "http://woeid.rosselliot.co.nz/lookup"
url = '%(U)s/%(I)s' % {'U': baseurl, "I": userInput}