接着昨天的项目,今天扩展下功能,爬取一个版面的所有文章。
import requests
import re
from bs4 import BeautifulSoup
def get_html(html_url):
'''获取html文本'''
res = requests.get(html_url)
res.encoding = "utf-8" # 以utf-8的编码格式来解析网页
return res.text
def get_article_url(layout_url):
bs = BeautifulSoup(get_html(layout_url), "html.parser")
ul = bs.find("ul", class_="news-list")
a = ul.find_all("a")
print(type(a[1]))
return [s['href'] for s in a]
def get_content(content_url):
'''从文章内容页获取文章正文'''
pat = r'<!--enpcontent-->([\s\S]*?)<!--/enpcontent-->'
wz = re.search(pat, get_html(content_url))
return wz.group(1)
# print(get_article_url(layout_url))
layout_url = r"http://paper.people.com.cn/rmrb/html/2020-09/11/nbs.D110000renmrb_01.htm" # 版面url
dly_base_url = r"http://paper.people.com.cn/rmrb/html/2020-09/11/"
article_urls = get_article_url(layout_url)
for u in article_urls:
complete_article_url = dly_base_url + u
content = get_content(complete_article_url)
print(repr(content[:55]))
输出结果:
<class 'bs4.element.Tag'>
'<P>\u3000\u3000中国人均水资源量是世界人均的1/4,而西海固,又是全国人均的1/23。西海固苦旱,吃水最难。然而去年'
……
今天遇到的新问题:
- 昨天用的正则表达式不能用了
'<!--enpcontent-->(.*)<!--/enpcontent-->'
需要换成:
'<!--enpcontent-->([\s\S]*?)<!--/enpcontent-->'
因为我发现一些文章里有换行符\n
写代码中遇到的问题:
- 因为换行符的存在,在print()输出文章时,会出现莫名其妙的断行。
- 定义的函数没考虑各种异常情况,而现实中会有各种各样的异常,我感觉做爬虫很容易遇到各种特殊情况,所以调试,错误处理的技巧很重要。
ps: 今天写这点又花了很久,看来每日10行代码的目标也不是很轻松,有时可能为了写出有效的代码,需要写几倍的代码来测试修改。