我創建了一個谷歌警報來生成一個 RSS 提要,看起來像這樣 https://www.google.co.in/alerts/feeds/17901041985790143983/2214023096042963178
現在如何使用 scrapy 從提要中的每個條目中提取標題、href、發布日期和內容?
我努力了:
import scrapy
class GalertCovidSpider(scrapy.Spider):
name = 'galert-covid'
allowed_domains = ['https://www.google.co.in/alerts/feeds/17901041985790143983/2214023096042963178']
start_urls = ['https://www.google.co.in/alerts/feeds/17901041985790143983/2214023096042963178/']
def start_requests(self):
urls = [
'https://www.google.co.in/alerts/feeds/17901041985790143983/2214023096042963178',
]
for url in urls:
yield scrapy.Request(url=url, callback=self.parse)
def parse(self, response):
for post in response.xpath('//feed/entry'):
yield {
'title' : post.xpath('title//text()').extract_first(),
'link': post.xpath('link//text()').extract_first(),
}
但是當我使用scrapy crawl --nolog --output -:json galert-covid它運行它時,它不會產生沒有錯誤的輸出。
抓取資訊后...如何繼續將抓取的資訊存盤到資料框或 CSV 中?
uj5u.com熱心網友回復:
我確信 Scrapy 可以做到這一點,但你不必使用它,這應該可以完成作業:
import requests
from bs4 import BeautifulSoup
import pandas as pd
name = 'galert-covid'
url = 'https://www.google.co.in/alerts/feeds/17901041985790143983/2214023096042963178'
resp = requests.get(url)
soup = BeautifulSoup(resp.text,'html.parser')
output = []
for entry in soup.find_all('entry'):
item = {
'title' : entry.find('title',{'type':'html'}).text,
'pubdate' : entry.find('published').text,
'content' : entry.find('content').text,
'link' : entry.find('link')['href']
}
output.append(item)
df = pd.DataFrame(output)
df.to_csv('google_alert.csv',index=False)
print('Saved to google_alert.csv')
uj5u.com熱心網友回復:
import scrapy
class GalertCovidSpider(scrapy.Spider):
name = 'galert-covid'
allowed_domains = ['www.google.co.in']
start_urls = ['https://www.google.co.in/alerts/feeds/17901041985790143983/2214023096042963178/']
custom_settings = {
'FEEDS': {
'galert-covid': {'format': 'csv'}
}
}
def start_requests(self):
for url in self.start_urls:
yield scrapy.Request(url=url)
def parse(self, response):
response.selector.remove_namespaces()
for post in response.xpath('//feed/entry'):
yield {
'title': post.xpath('.//title//text()').get(),
'link': post.xpath('.//link/@href').get(),
'published date': post.xpath('.//published/text()').get(),
'content': post.xpath('.//content/text()').get(),
}
閱讀有關洗掉名稱空間和提要的資訊。
allowed_domains應該只是域,我洗掉了里面的默認回呼(start_requests沒有必要,我只是喜歡這樣),并且在 yield 我添加了一個點來獲取相對 xpaths。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/415715.html
標籤:
上一篇:熊貓:如何正確取消df?
下一篇:回圈多個字符列以派生新變數
