【发布时间】:2019-05-12 16:47:14
【问题描述】:
我需要从 Le Monde 报纸的档案(从 1980 年开始)中刮掉所有关于自闭症主题的头条新闻。 我不是程序员,而是试图成为“数字化”的人道主义者......
我设法获得了所有(每日)问题的列表,并且从另一方面来说,一次用汤解析一个 url 并提取标题也可以。但两者一起没有。 我的问题是在解析+迭代步骤上,但无法解决。
from bs4 import BeautifulSoup
import requests
import re
from datetime import date, timedelta
start = date(2018, 1, 1)
end = date.today()
all_url =[]
#this chunk is working and returns a nice list of all url of all issues
day = timedelta(days=1)
one_url = "https://www.lemonde.fr/archives-du-monde/"
mydate = start
while mydate < end:
mydate += day
if one_url not in all_url:
all_url.append(one_url + "{date.day:02}/{date.month:02}/{date.year}".format(date=mydate) + '/')
#this function is working as well when applied with one single url
def titles(all_url):
for url in all_url:
page = BeautifulSoup(requests.get(url).text, "lxml")
regexp = re.compile(r'^.*\b(autisme|Autisme)\b.*$')
for headlines in page.find_all("h3"):
h = headlines.text
for m in regexp.finditer(h):
print(m.group())
titles(all_url)
这个脚本卡住了...
【问题讨论】:
-
这段代码中的开始日期是2018年初,以便于运行...
-
脚本需要一段时间才能运行,它没有卡住。您可以在
title函数的外循环中添加print,以检查它是否仍在运行。但是我确实注意到 Le Monde 似乎使用以01-01-2018格式的日期结尾的 url 作为其存档,因此更改那里的分隔符可能会有所帮助。 -
我刚刚从去年到今天(496 个 url)运行了脚本,在我的机器上花了将近 5 分钟。
标签: python beautifulsoup