python爬取新闻标题的代码
时间: 2023-07-10 13:14:21 浏览: 56
可以使用Python的requests和BeautifulSoup库来爬取新闻标题,具体代码如下:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://news.baidu.com/'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
news_list = soup.find_all('a', class_='title')
for news in news_list:
print(news.text)
```
这段代码会爬取百度新闻首页的所有新闻标题,并把它们打印出来。当然,你也可以将其保存到文件中或者进行其他的处理。
相关问题
python爬取新闻标题
你可以使用 Python 中的 requests 和 BeautifulSoup 库来爬取新闻标题。下面是一个简单的示例代码:
```python
import requests
from bs4 import BeautifulSoup
url = "http://www.xinhuanet.com/"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
# 找到所有的新闻标题
titles = soup.find_all("a", class_="title")
# 输出新闻标题
for title in titles:
print(title.text)
```
这个代码会爬取新华网的首页,并输出所有新闻标题。你可以根据需要修改代码中的 URL 和选择器来适应不同的网站。注意,爬取网站内容时需要遵守法律法规和网站的访问限制。
python xpath爬取新闻标题
以下是一个示例代码,可以使用Python和XPath爬取新闻标题:
```python
import requests
from lxml import etree
url = 'https://www.baidu.com/s?wd=%E6%96%B0%E9%97%BB&tn=news&ie=UTF-8'
response = requests.get(url)
html = response.content
tree = etree.HTML(html)
# 使用XPath选择新闻标题
titles = tree.xpath('//h3[@class="news-title_1YtI1"]/a/text()')
# 打印新闻标题
for title in titles:
print(title)
```
解释一下代码:
1. 首先,我们需要导入requests和lxml.etree模块,因为我们将使用它们来爬取并解析HTML。
2. 然后,我们指定了要爬取的网址,并使用requests.get()函数从该网址获取响应。
3. 我们使用response.content将响应的HTML内容存储在一个变量中。
4. 接下来,我们使用etree.HTML()函数将HTML字符串转换为lxml.etree.Element对象,这样我们就可以使用XPath表达式来选择HTML元素。
5. 然后,我们使用XPath表达式选择所有具有“news-title_1YtI1”类的<h3>元素,并从每个元素中提取文本内容。
6. 最后,我们将每个标题打印到控制台。
请注意,上面的代码仅适用于百度新闻搜索结果页面。如果您想爬取其他网站的新闻标题,您需要根据该网站的HTML结构修改XPath表达式。