Python应用-爬虫实战-求是网周刊文章爬取

抓取《求是》2019年第一期新闻URL:正则与网页解析实战,
该文章已生成可运行项目,

第1关:获取新闻url

任务描述

本关任务:编写一个爬虫,并使用正则表达式获取求是周刊2019年第一期的所有文章的url。详情请查看《求是》2019年第1期 

相关知识

获取每个新闻的url有以下几个步骤:

  • 首先获取2019年第1期页面的源码,需要解决部分反爬机制;

  • 找到目标url所在位置,观察其特征;

  • 编写正则表达式,获取目标数据。

编程要求

根据提示,在右侧编辑器Begin-End处补充代码,使用正则表达式获取求是周刊2019年第一期的所有文章的url,返回的是一个包含所有url的列表。

测试说明

补充完代码后,点击测评,平台会对你编写的代码进行测试,当你的结果与预期输出一致时,即为通过。

预期输出:

 
  1. http://www.qstheory.cn/dukan/qs/2019-01/01/c_1123924154.htm
  2. http://www.qstheory.cn/dukan/qs/2018-12/31/c_1123923896.htm
  3. http://www.qstheory.cn/dukan/qs/2019-01/01/c_1123923886.htm
  4. http://www.qstheory.cn/dukan/qs/2019-01/01/c_1123923852.htm
  5. http://www.qstheory.cn/dukan/qs/2019-01/01/c_1123923828.htm
  6. http://www.qstheory.cn/dukan/qs/2019-01/01/c_1123923817.htm
  7. http://www.qstheory.cn/dukan/qs/2019-01/01/c_1123923778.htm
  8. http://www.qstheory.cn/dukan/qs/2019-01/01/c_1123923740.htm
  9. http://www.qstheory.cn/dukan/qs/2019-01/01/c_1123923715.htm
  10. http://www.qstheory.cn/dukan/qs/2019-01/01/c_1123923686.htm
  11. http://www.qstheory.cn/dukan/qs/2019-01/01/c_1123922609.htm
  12. http://www.qstheory.cn/dukan/qs/2019-01/01/c_1123922550.htm
  13. http://www.qstheory.cn/dukan/qs/2019-01/01/c_1123922484.htm
  14. http://www.qstheory.cn/dukan/qs/2019-01/01/c_1123922467.htm
  15. http://www.qstheory.cn/dukan/qs/2019-01/01/c_1123922434.htm
  16. http://www.qstheory.cn/dukan/qs/2019-01/01/c_1123924169.htm

开始你的任务吧,祝你成功!

此题需要用到正则表达式,以及soup中获取属性的函数get('href')

上代码:

import requests
import bs4
import re

headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36 Edg/118.0.2088.76'
}
def geturls():
    # ********** Begin ********** #

    responde = requests.get(f'http://www.qstheory.cn/dukan/qs/2014/2019-01/01/c_1123924172.htm')
    responde.encoding ='utf-8'
    content = responde.text
    soup = bs4.BeautifulSoup(content,'html.parser')

    all_a = soup.find_all('a')
    urls = []
    for a in all_a:
        if re.findall(r'\w*dukan\w*', a.get('href')) and '1123932149' not in str(a.get('href')):
            urls.append(a.get('href'))

    # ********** End ********** #
    return urls

if __name__ == "__main__":
    urls = geturls()
    for x in urls:
        print(x)

 第2关:获取文章内容

任务描述

本关任务:编写一个爬虫,请求上一关获取的每个url,获取每篇文章的标题、作者、正文以及文章中全部图片的完整url

相关知识

为了完成本关任务,你需要掌握xpath的基本使用。

选取节点:

路径表达式结果
bookstore选取 bookstore 元素的所有子节点
/bookstore选取根元素 bookstore。注:假如路径起始于正斜杠( / ),则此路径始终代表到某元素的绝对路径!
bookstore/book选取属于 bookstore 的子元素的所有 book 元素。
//book选取所有 book 子元素,而不管它们在文档中的位置。
bookstore//book选择属于 bookstore 元素的后代的所有 book 元素,而不管它们位于 bookstore 之下的什么位置。
//@lang选取名为 lang 的所有属性。

谓语:

路径表达式结果
/bookstore/book[1]选取属于 bookstore 子元素的第一个 book 元素。
/bookstore/book[last()]选取属于 bookstore 子元素的最后一个 book 元素。
/bookstore/book[last()-1]选取属于 bookstore 子元素的倒数第二个 book 元素。
/bookstore/book[position()<3]选取最前面的两个属于 bookstore 元素的子元素的 book 元素。
//title[@lang]选取所有拥有名为 lang 的属性的 title 元素。
//title[@lang='eng']选取所有 title 元素,且这些元素拥有值为 eng 的 lang 属性。
/bookstore/book[price>35.00]选取 bookstore 元素的所有 book 元素,且其中的 price 元素的值须大于 35.00。
/bookstore/book[price>35.00]/title选取 bookstore 元素中的 book 元素的所有 title 元素,且其中的 price 元素的值须大于 35.00。

选取未知节点:

路径表达式结果
/bookstore/*选取 bookstore 元素的所有子元素。
//*选取文档中的所有元素。
//title[@*]选取所有带有属性的 title 元素。

编程要求

根据提示,在右侧编辑器Begin...End中补充代码,请求上一关获取的每个url,将每篇文章的标题、作者、正文以及文章中全部图片的完整url,并按照以下格式保存:

。。。。。。

测试说明

补充完代码后,点击测评,平台会对你编写的代码进行测试,当你的结果与预期输出一致时,即为通过。

在代码中我使用了xpath的查询语句和BeautifulSoup,感觉混合使用比较方便哈哈哈,还是功夫不到家。

上代码:

import requests
import bs4
import re
from lxml import etree


def parsepage(urls):
    mainbody = []
    headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36 Edg/118.0.2088.76'
}
    for url in urls:
        response = requests.get(url, headers=headers)
        response.encoding = 'utf-8'
        soup = bs4.BeautifulSoup(response.text,'html.parser')
        tree = etree.HTML(response.text)

        # 获取图片的url
        img_urls = tree.xpath('//div[@class="highlight"]//img/@src')
        # 获取标题并去除首尾空格

        title = tree.xpath('//h1/text()')[0].strip()

        # 获取作者并去除首尾空格
        author = tree.xpath('//span[@class="appellation"]/text()')[1].strip()[3:]
        
        #获取正文内容
        content_t =''
        for p in soup.find_all('p'):
            content_t += p.text.strip()

        #保存提取的信息
        mainbody.append({
            'title': title,
            'author': author,
            'content': content_t,
            'imgurl': img_urls
        })
    return mainbody

都看到这里了,点个赞不过分吧( •̀ ω •́ )✧

本文章已经生成可运行项目
### 使用爬虫技术从求是爬取周刊文章实战教程 为了实现从求是爬取周刊文章的目标,可以采用 Python 的 `requests` 和 `BeautifulSoup` 库完成基本的数据提取工作。以下是详细的代码示例以及解释: #### 准备环境 首先需要安装必要的库: ```bash pip install requests beautifulsoup4 lxml ``` #### 编写爬虫代码 以下是一个完整的代码示例,用于从求是爬取周刊文章的内容。 ```python import requests from bs4 import BeautifulSoup def fetch_weekly_articles(url): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' } try: response = requests.get(url, headers=headers) response.raise_for_status() response.encoding = 'utf-8' # 设置编码方式 soup = BeautifulSoup(response.text, 'lxml') articles = [] article_list = soup.find_all('div', class_='article') # 替换为实际的文章列表容器类名[^3] for article in article_list: title = article.find('h2').get_text(strip=True) if article.find('h2') else None link = article.find('a')['href'] if article.find('a') and 'href' in article.find('a').attrs else None summary = article.find('p').get_text(strip=True) if article.find('p') else None if title and link: articles.append({ 'title': title, 'link': link, 'summary': summary }) return articles except Exception as e: print(f"Error occurred while fetching data from {url}: {e}") return [] if __name__ == "__main__": url = "https://www.qstheory.cn/" # 替换为目标址 weekly_articles = fetch_weekly_articles(url) for idx, article in enumerate(weekly_articles[:10], start=1): # 输出前10篇文章作为示例 print(f"{idx}. Title: {article['title']} | Link: {article['link']} | Summary: {article['summary']}") ``` 以上代码实现了以下几个功能: 1. 发送 HTTP 请求到目标 URL 解析 HTML 页面内容。 2. 利用 `BeautifulSoup` 提取页面中的文章标题、链接和摘要信息。 3. 将结果存储在一个字典列表中以便后续处理或展示。 需要注意的是,在实际应用过程中可能需要调整 CSS 选择器以匹配具体的页结构[^3]。 #### 数据保存至本地文件 如果希望将爬取的结果保存到本地文件中,可以在程序最后加入如下逻辑: ```python with open("articles.txt", "w", encoding="utf-8") as f: for article in weekly_articles: f.write(f"Title: {article['title']}\nLink: {article['link']}\nSummary: {article['summary']}\n\n") print("Articles have been saved to articles.txt.") ``` 这会将每一篇文章的信息按指定格式写入名为 `articles.txt` 的文本文件中。 --- ### 注意事项 在编写爬虫时需注意遵守目标站的服务条款及法律法规,避免因频繁请求或其他不当行为引发法律风险或被封禁 IP 地址等问题[^3]。 ---
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值