爬取界面中“贵州茅台”相关新闻的标题、网址和日期。

1 需求

爬取界面中“贵州茅台”相关新闻的标题、网址和日期。

2 代码实现

import re

from selenium import webdriver


chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
browser = webdriver.Chrome(options=chrome_options)

# 获取网页源代码
url = 'https://a.jiemian.com/index.php?m=search&a=index&msg=贵州茅台&type=news'
browser.get(url=url)
data = browser.page_source

# 获取网页标题
p_title = '<div class="news-header">.*?title="(.*?)">'
title = re.findall(p_title, data)

# 获取网页网址
p_href = '<div class="news-view.*?href="(.*?)" target="_blank"'
href = re.findall(p_href, data)

# 获取新闻日期
p_date = '<span class="date">(.*?)</span>'
date = re.findall(p_date, data)

# 数据整理
for index in range(len(title)):
    print(str(index + 1) + "." + title[index] + "(" + date[index] + ")")
    print(href[index])
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是爬取京东贵州茅台商品评论数据的示例代码: ```python import requests import json from lxml import etree # 商品ID product_id = '100016496848' # 请求头 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36', 'Referer': f'https://item.jd.com/{product_id}.html', 'Host': 'club.jd.com' } # 评论API url = f'https://club.jd.com/comment/productPageComments.action?productId={product_id}&score=0&sortType=5&page=0&pageSize=10' # 发起请求 response = requests.get(url, headers=headers) # 获取评论数 comment_count = json.loads(response.text)['productCommentSummary']['commentCount'] # 获取页数 page_count = (comment_count + 9) // 10 # 爬取评论 comments = [] for page in range(page_count): url = f'https://club.jd.com/comment/productPageComments.action?productId={product_id}&score=0&sortType=5&page={page}&pageSize=10' response = requests.get(url, headers=headers) html = etree.HTML(response.text) comment_list = html.xpath('//div[@class="comment-item"]') for comment in comment_list: content = comment.xpath('.//div[@class="comment-con"]/div/text()')[0] comments.append(content.strip()) # 打印评论 for comment in comments: print(comment) ``` 代码说明: 1. 首先,我们需要获取商品ID,可以在京东商品页面的URL找到。例如,商品页面URL为`https://item.jd.com/100016496848.html`,则商品ID为`100016496848`。 2. 我们需要发起请求获取评论数据。评论API的URL为`https://club.jd.com/comment/productPageComments.action`。其,`productId`参数为商品ID,`score`参数为评分,`sortType`参数为排序方式,`page`参数为页数,`pageSize`参数为每页评论数。 3. 首先,我们需要获取评论总数以及页数,然后循环爬取每一页的评论。 4. 我们使用XPath解析HTML代码,获取每条评论的内容。最后,将评论内容存储到列表。 5. 最后,打印评论内容。 需要注意的是,由于京东的反爬虫机制比较严格,我们需要设置请求头,模拟浏览器发起请求。同时,为了避免被封IP,我们可以设置延时等策略。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值