php 抓取网页标题(python爬虫爬取爬取网页新闻标题方法网页方法)
优采云 发布时间: 2021-12-10 10:05php 抓取网页标题(python爬虫爬取爬取网页新闻标题方法网页方法)
Python爬虫抓取网页新闻标题的方法
1.首先,使用浏览-检查提供的工具查找与网页新闻标题对应的元素位置。这里的新闻标题在H3标签中
2.然后使用编辑器编写Python代码
2.1方法1:
import requests
from bs4 import BeautifulSoup
url = 'http://www.xxx.com/'
r = requests.get(url)
r.encoding = 'utf-8'
soup = BeautifulSoup(r.text,'html.parser') # 'html.parser'这是BeautifulSoup库的HTML解析器的用法,用于解析HTML
#print(r.text)
titles = soup.select('h3')
for title in titles: # 使用循环输出爬取到的网页上的所有新闻标题
print(title.text)
2.2方法2:
#coding = utf-8
import requests
from lxml import etree
url = 'http://www.xxx.com/'
r = requests.get(url)
html = etree.HTML(r.text)
titles = html.xpath('//div[@class="box-seven"]//h3/text()')
for title in titles:
print('Title:', title)
3.总结:
以上两种方法都可以实现抓取网络新闻标题的功能。如果有用的话,你可以关注我。如果您有问题,可以留下私人消息进行交流