[英]Storing in csv through Scrapy
我正在學習web scraping through Scrapy。我一直卡在問題如下:
為什么 CSV 文件會在一行中打開整個數據? 實際上它應該有 8 行和 4 列。 列沒問題,但我不明白為什么它只打開一行中的數據。
import scrapy
class MyredditSpider(scrapy.Spider):
name = 'myreddit'
allowed_domains = ['reddit.com']
start_urls = ['http://www.reddit.com/']
#custom_settings = {
#"FEEDS":{"result.csv":{"format":"csv",}}
#}
def parse(self, response):
all_var=response.xpath("//div[@class='rpBJOHq2PR60pnwJlUyP0']")
for variable in all_var:
post= variable.xpath("//h3[@class='_eYtD2XCVieq6emjKBH3m']/text()").extract()
vote= variable.xpath("//div[@class='_1rZYMD_4xY3gRcSS3p8ODO _3a2ZHWaih05DgAOtvu6cIo ']/text()").extract()
time=variable.xpath("//span[@class='_2VF2J19pUIMSLJFky-7PEI']/text()").extract()
links= variable.xpath("//a[@data-click-id='body']/@href").extract()
yield{"Posts": post, "Votes": vote, "Time": time, "Links":links}
我使用scrapy crawl myreddit -o items.csv將數據保存在 csv 中。我想相應地獲取 CSV 中的每個值。 和圖片差不多
您的代碼看起來不錯,並且可以正常工作。 yield
是單行的術語。 每當您在代碼中使用 yield 作為 output 時,它將被視為單行。 下面的示例將 output 兩行。
yield{"Posts": post}
yield {"Votes": vote, "Time": time, "Links":links}
可能 scrapy 將整個數據表打開為一個,因為分隔符arguments 不正確。 delimiter
的默認參數設置為","
並用逗號分隔數據。
請記住,如果抓取的數據包含逗號,則滑動過程會導致不需要的列。
如果是這種情況,您可以使用類似"|"
的內容或"\t"
作為分隔符。
另一方面,問題可能出在您的l.neterminator
參數上,該參數指示每行數據應如何終止。 此參數的默認值為"\r\n"
。
如果您的數據不使用這些字符作為l.neterminators
,您可以使用其他字符,例如"\n"
,以確保數據被分成不同的行。
請參見下面的示例:
from scrapy.exporters import CSVItemExporter
# Use the "|" as the delimiter and "\n" as the lineterminator
exporter = CSVItemExporter(delimiter="|", lineterminator="\n")
exporter.export_item(item)
這是因為那是您提取信息的方式...
您的每個extract()
調用都會同時提取頁面上的所有這些元素,如果您希望逐行列出它們,您也需要逐行遍歷 html 元素。
例如,它應該看起來更接近於它迭代每一行並從每一行中提取信息並產生它然后移動到下一行的地方。
import scrapy
class MyredditSpider(scrapy.Spider):
name = 'myreddit'
allowed_domains = ['reddit.com']
start_urls = ['http://www.reddit.com/']
def parse(self, response):
for row in response.xpath('//div[@class="rpBJOHq2PR60pnwJlUyP0"]/div'):
post = row.xpath(".//h3[@class='_eYtD2XCVieq6emjKBH3m']/text()").get()
vote = row.xpath(".//div[@class='_1rZYMD_4xY3gRcSS3p8ODO _3a2ZHWaih05DgAOtvu6cIo ']/text()").get()
time = row.xpath(".//span[@class='_2VF2J19pUIMSLJFky-7PEI']/text()").get()
links = row.xpath(".//a[@data-click-id='body']/@href").get()
yield {"Posts": post, "Votes": vote, "Time": time, "Links":links}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.