【发布时间】: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