1 Star 0 Fork 0

红色四叶草/spider

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
weathers.py 1.68 KB
一键复制 编辑 原始数据 按行查看 历史
红色四叶草 提交于 2020-05-11 09:23 +08:00 . 爬取中国天气网
import requests
from bs4 import BeautifulSoup
def parse_page(url):
url = 'http://www.weather.com.cn/textFC/hn.shtml'
headers = {
'User-Agent': "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"}
response = requests.get(url, headers=headers)
# print(response.content.decode('utf-8'))
text = response.content.decode('utf-8')
soup = BeautifulSoup(text, 'html5lib')
# print(soup)
conMidtab = soup.find('div', class_="conMidtab")
tables = conMidtab.find_all('table')
# print(tables)
for table in tables:
trs = table.find_all('tr')[2:]
#print(trs)
for index, tr in enumerate(trs):
# for tr in trs:
tds = tr.find_all('td')
city_td = tds[0]
#print(city_td)
if index == 0:
city_td = tds[1]
city = list(city_td.stripped_strings)[0]
weather_td = tds[1]
if index == 0:
weather_td = tds[2]
weather_td = list(weather_td.stripped_strings)[0]
print({ "city" : city, "weather" : weather_td })
def main():
urls = {'http://www.weather.com.cn/textFC/hb.shtml',
'http://www.weather.com.cn/textFC/hn.shtml',
'http://www.weather.com.cn/textFC/db.shtml',
'http://www.weather.com.cn/textFC/hd.shtml',
'http://www.weather.com.cn/textFC/hz.shtml',
'http://www.weather.com.cn/textFC/xb.shtml',
'http://www.weather.com.cn/textFC/xn.shtml',
'http://www.weather.com.cn/textFC/gat.shtml'}
for url in urls:
parse_page(url)
if __name__ == '__main__':
main()
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/prototype-gfc/spider.git
git@gitee.com:prototype-gfc/spider.git
prototype-gfc
spider
spider
master

搜索帮助