python爬虫爬去新闻
时间: 2023-10-01 13:05:25 浏览: 47
爬虫是一种自动化程序,可以通过获取网页内容并提取所需的信息。Python语言由于其简洁易学的特点,成为爬虫工具的首选语言。要使用Python进行新闻爬取,你可以使用Python的一些库,例如`urllib`和`BeautifulSoup`。`urllib`库可以用来发起HTTP请求并获取网页内容,而`BeautifulSoup`库可以用来解析网页内容并提取所需的信息。下面是一个爬取新浪新闻的示例代码:
```python
import urllib.request
from bs4 import BeautifulSoup
# 发起HTTP请求获取网页内容
url = "http://news.sina.com.cn/"
response = urllib.request.urlopen(url)
html = response.read()
# 解析网页内容并提取新闻标题
soup = BeautifulSoup(html, "html.parser")
news_titles = soup.find_all("a", class_="news-item")
for news in news_titles:
print(news.text)
```
相关问题
python爬虫爬新闻标题
要使用Python爬虫来爬取新闻标题,你可以引入requests模块来发送HTTP请求获取网页内容,然后使用正则表达式或者BeautifulSoup库来解析网页,提取新闻标题。
以下是一个示例代码,可以帮助你实现这个功能:
```
import requests
import re
def get_news_titles(url):
response = requests.get(url)
html_content = response.text
titles = re.findall('<h2 class="title">(.*?)</h2>', html_content)
return titles
news_url = "https://www.example.com/news"
news_titles = get_news_titles(news_url)
for title in news_titles:
print(title)
```
python爬虫爬腾讯新闻用scrapy
以下是使用Scrapy爬取腾讯新闻的步骤:
1. 创建Scrapy项目
在命令行中执行以下命令来创建一个名为tencent_news的Scrapy项目:
```
scrapy startproject tencent_news
```
2. 创建Spider爬虫
在命令行中执行以下命令来创建一个名为tencent的Spider爬虫:
```
scrapy genspider tencent news.qq.com
```
这里的news.qq.com是腾讯新闻的域名,可以根据需要进行修改。
3. 编写Spider爬虫
打开tencent/spiders/tencent.py文件,根据需要编写Spider爬虫的代码。以下是一个简单的示例:
```python
import scrapy
class TencentSpider(scrapy.Spider):
name = 'tencent'
allowed_domains = ['news.qq.com']
start_urls = ['https://news.qq.com/']
def parse(self, response):
# 解析新闻列表页
for news in response.xpath('//div[@class="Q-tpList"]/ul/li'):
yield {
'title': news.xpath('a/text()').get(),
'url': news.xpath('a/@href').get(),
'datetime': news.xpath('span/text()').get(),
}
# 获取下一页链接并继续爬取
next_page = response.xpath('//a[@class="page-next"]/@href')
if next_page:
yield response.follow(next_page[0], self.parse)
```
这个Spider爬虫会爬取腾讯新闻首页的新闻列表,并将每条新闻的标题、链接和发布时间保存到一个字典中。
4. 运行Spider爬虫
在命令行中进入tencent_news目录,执行以下命令来运行Spider爬虫:
```
scrapy crawl tencent
```
Spider爬虫会开始爬取腾讯新闻,并将结果输出到命令行中。