【发布时间】:2020-09-07 18:47:38
【问题描述】:
我想抓取一个法国网站上的数据,结果只有 50 篇文章。这个网站有50多篇文章。我哪里错了?
我的目标是爬取本站所有文章。
我试过了:
import newspaper
legorafi_paper = newspaper.build('http://www.legorafi.fr/', memoize_articles=False)
# Empty list to put all urls
papers = []
for article in legorafi_paper.articles:
papers.append(article.url)
print(legorafi_paper.size())
这次打印的结果是 50 篇文章。
我不明白为什么newspaper3k 只会抓取 50 篇文章而不是更多。
我尝试过的更新:
def Foo(firstTime = []):
if firstTime == []:
WebDriverWait(driver, 30).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"div#appconsent>iframe")))
firstTime.append('Not Empty')
else:
print('Cookies already accepted')
%%time
categories = ['societe', 'politique']
import time
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
import newspaper
import requests
from newspaper.utils import BeautifulSoup
from newspaper import Article
categories = ['people', 'sports']
papers = []
driver = webdriver.Chrome(executable_path="/Users/name/Downloads/chromedriver 4")
driver.get('http://www.legorafi.fr/')
for category in categories:
url = 'http://www.legorafi.fr/category/' + category
#WebDriverWait(self.driver, 10)
driver.get(url)
Foo()
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.button--filled>span.baseText"))).click()
pagesToGet = 2
title = []
content = []
for page in range(1, pagesToGet+1):
print('Processing page :', page)
#url = 'http://www.legorafi.fr/category/france/politique/page/'+str(page)
print(driver.current_url)
#print(url)
time.sleep(3)
raw_html = requests.get(url)
soup = BeautifulSoup(raw_html.text, 'html.parser')
for articles_tags in soup.findAll('div', {'class': 'articles'}):
for article_href in articles_tags.find_all('a', href=True):
if not str(article_href['href']).endswith('#commentaires'):
urls_set.add(article_href['href'])
papers.append(article_href['href'])
for url in papers:
article = Article(url)
article.download()
article.parse()
if article.title not in title:
title.append(article.title)
if article.text not in content:
content.append(article.text)
#print(article.title,article.text)
time.sleep(5)
driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")
driver.find_element_by_xpath("//a[contains(text(),'Suivant')]").click()
time.sleep(10)
【问题讨论】:
-
Stackoverflow有特殊的方法(和快捷键)来格式化多行代码。 -
网站可能会在一些计数后阻止您,您可以联系他们的网络管理员,他们可以提供比您可以抓取的更好的集合,如果您正在做一些科学或学习他们可能是免费的可以从中受益!
-
谢谢@ti7 你知道我能不能用python代码绕过它吗?
-
@LJRB 您可以使用proxy or proxies,这将允许您的程序充当多个独立客户端而不是单个客户端。但是,直接要求更好地访问数据(可能就像没有 50 页限制的帐户一样简单)并在您正在制作的作品中引用它们可能就是他们要求您获得更高质量访问的全部内容(他们知道任何人都可以编写程序来阅读他们的网站,如果你有一个网站,你会看到许多机器人正在积极地阅读你的网站)。
标签: python newspaper3k