【问题标题】:How can I save the response as csv without "\n" being displayed?如何在不显示“\n”的情况下将响应保存为 csv?
【发布时间】:2020-12-14 21:07:45
【问题描述】:

这个脚本的输出有问题。返回响应时,“详细信息”响应始终包含短语“\n”。如何在没有“\n”的情况下将响应保存为 csv?感谢您的任何建议。

from requests_html import HTMLSession

def getPrice(url):
    s = HTMLSession()
    r = s.get(url)
    r.html.render(sleep=1)

    product = {
        'title': r.html.xpath('//*[@id="productTitle"]', first=True).text,
        'price': r.html.xpath('//*[@id="priceblock_ourprice"]', first=True).text,
        'details': r.html.xpath('//*[@id="prodDetails"]/div/div[1]/div', first=True).text
    }

    print(product)
    return product

getPrice('https://www.amazon.com/dp/B07HXN1V51')

追溯

{'title': 'Charades Party Game – Speed Charades Board Game – Fast-Paced Party Game - Perfect for Groups and Family Game Nights', 'price': '$24.99', 'details': 'Product Dimensions\n10.25 x 8.5 x 2.6 inches\nItem Weight\n1.75 pounds\nASIN\nB07HXN1V51\nItem model number\n8291\nManufacturer recommended age\n13 years and up\nBest Sellers Rank\n#2,811 in Toys & Games (See Top 100 in Toys & Games)\n#191 in Board Games (Toys & Games)\n\nCustomer Reviews\n/* * Fix for UDP-1061. Average customer reviews has a small extra line on hover * https://omni-grok.amazon.com/xref/src/appgroup/websiteTemplates/retail/SoftlinesDetailPageAssets/udp-intl-lock/src/legacy.css?indexName=WebsiteTemplates#40 */ .noUnderline a:hover { text-decoration: none; }\n4.7 out of 5 stars 682 ratings P.when(\'A\', \'ready\').execute(function(A) { A.declarative(\'acrLink-click-metrics\', \'click\', { "allowLinkDefault" : true }, function(event){ if(window.ue) { ue.count("acrLinkClickCount", (ue.count("acrLinkClickCount") || 0) + 1); } }); }); P.when(\'A\', \'cf\').execute(function(A) { A.declarative(\'acrStarsLink-click-metrics\', \'click\', { "allowLinkDefault" : true }, function(event){ if(window.ue) { ue.count("acrStarsLinkWithPopoverClickCount", (ue.count("acrStarsLinkWithPopoverClickCount") || 0) + 1); } }); });\n\n4.7 out of 5 stars\nIs Discontinued By Manufacturer\nNo\nMfg Recommended age\n13 year and up\nManufacturer\nThe GAME CHEF'}

【问题讨论】:

  • 您的问题不清楚:您希望该响应看起来像 csv 行吗?
  • @JackFleeting 嗨,我希望响应采用电子表格格式,列为标题、价格、详细信息,数据位于行中。这有意义吗?
  • 你试过这样' '.join(r.html.xpath('//*[@id="prodDetails"]/div/div[1]/div', first=True).text.split())

标签: python python-3.x csv web-scraping python-requests


【解决方案1】:

假设您的字典值只是字符串,那么我将使用替换。

举例

res = {}
for key in list(product):
    res[key] = product[key].replace('\n',' ')

print(res)
return res

关于替换方法的更多信息:

也许可以就地进行转换,我不记得字典是否允许这样做。

编辑

保存为 csv:

import pandas as pd

df = pd.DataFrame(products)
df.to_csv('my_products_csv.csv')

【讨论】:

  • 您好,您提供的替换脚本不会替换换行符。你能提供更多解释吗?
  • 我不确定您的r.html.xpath().text 操作的数据类型输出是什么,因此您可能需要将所有这些都包含在字符串转换中,例如str(r.html.xpath().text)。否则,替换方法是python中字符串对象的原生方法
【解决方案2】:

试试这个来摆脱由脚本和样式标签产生的乱码。此外,换行问题已得到处理。我将bs4 库与requests_html 结合使用来剔除不需要的标签。

from requests_html import HTMLSession
from bs4 import BeautifulSoup

def getPrice(url):
    s = HTMLSession()
    r = s.get(url)
    r.html.render(sleep=1)
    soup = BeautifulSoup(r.html.raw_html,"html.parser")

    [script.extract() for script in soup.select("script,style")]

    product = {
        'title': soup.select_one('span#productTitle').get_text(strip=True),
        'price': soup.select_one('#priceblock_ourprice').get_text(strip=True),
        'details': ' '.join(soup.select_one('table[class$="prodDetTable"]').text.split())
    }

    return product

print(getPrice('https://www.amazon.com/dp/B07HXN1V51'))

编辑:

我不确定这是否是您的意思:

try:
    title = soup.select_one('span#productTitle').get_text(strip=True)
except AttributeError: title = ''
try:
    price = soup.select_one('#priceblock_ourprice').get_text(strip=True)
except AttributeError: price = ''
try:
    details = ' '.join(soup.select_one('table[class$="prodDetTable"]').text.split())
except AttributeError: details = ''

product = {
    'title': title,
    'price': price,
    'details': details
}

【讨论】:

  • 如果标题、价格或详细信息部分不可用怎么办?如何实现 else 语句?
猜你喜欢
  • 2014-04-17
  • 2017-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多