当前位置: 首页 > 后端技术 > PHP

py爬取汽车之家新闻案例

时间:2023-03-30 04:15:07 PHP

importrequestsfrombs4importBeautifulSouresponse=requests.get("https://www.autohome.com.cn/news/")#1.content/text的区别#print(response.content)#content得到的字节response.encoding='gbk'#print(response.text)#text得到的文本信息soup=BeautifulSoup(response.text,'html.parser')#tag=soup.find(id='auto-channel-lazyload-article')#找到一个唯一的值并缩小范围#h3=tag.find(name='h3',class_='')#class是一个关键字所以下划线,或者使用下面的方法#h3=tag.find(name='h3',attrs={'class':''})##print(h3)#chainwritingli_list=soup.find(id='auto-channel-lazyload-article').find_all(name='li')forliinli_list:title=li.find('h3')#获取titleifnottitle:#如果为null则跳出继续title=title.textsummary=li.find("p").texturl=li.find("a").get('href')img=li.find("img").get('src')打印(img)#保存图片res=requests.get(img)file_name="%s.jpg"%(title,)withopen(file_name,'wb')asf:f.write(res.content)#Save字节内容更多更多精彩文章请关注王明昌的博客

猜你喜欢