python爬虫

三种解析方式:

1.正则表达式 re

格式:

obj = re.compile(r'<h\d><a href="/(?P<pname>.*?)/">(?P<cname>.*?)</a></h\d>', re.S)

result = obj.finditer(str(div_page))

for i in result:

    if i.group("pname")[0:9] != "province/":
print(i.group("cname"))
print(i.group("pname"))

 

2.靓汤 BeautifulSoup bs4

格式:

main_page = BeautifulSoup(resp.text, "html.parser")

div_page = main_page.find("div", class_="wrapbox")

div.page 返回的是"div", class_="wrapbox"里面的html内容

div.page.text 返回的是标签里面的内容

 

3.xpath lxml

html = etree.HTML(cresp.text)
li_list = html.xpath("/html/body/div[7]/div[2]/ul[1]/li")

 

保存csv文件

with open('city_weather.csv', 'w', newline='', encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(['时间', '天气', '最低温度', '最高温度'])
writer.writerows(all_list)
newline=''可以取消空行

posted @ 2021-08-18 12:49  hefuhao  阅读(46)  评论(0)    收藏  举报