【问题标题】:Extract image URL as a string using XPath使用 XPath 将图像 URL 提取为字符串
【发布时间】:2019-09-05 17:00:47
【问题描述】:

我无法使用 xpath 从 Flipkart 中提取产品图片网址。

网址:https://www.flipkart.com/f-d-f550x-56-w-bluetooth-home-theatre/p/itmea2aspwcaxuaz?pid=ACCEA2ASHNDGV4DP

目标是提取 src 包含的图片 url。

在这种情况下:https://rukminim1.flixcart.com/image/416/416/speaker/home-audio-speaker/4/d/p/f-d-a550x-original-imaea2ftzywquzrz.jpeg?q=70 应该是输出。

我使用的 Xpath 是:

//*[@class="_2rDnao"]//img[@src]

在 chrome xpath 助手中使用上面的 xpath 它给了我想要的输出,但是在 python 脚本中使用它时它会变成空白。

import requests
from lxml import html
import os


request_headers = {
"Accept-Language": "en-US,en;q=0.5",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0.15063; Win64; x64) 
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Referer": "http://thewebsite.com",
"Connection": "keep-alive" 
}


webpage=requests.get("https://www.flipkart.com/savehatke/p/itmea2aspwcaxuaz? 
pid=ACCEA2ASHNDGV4DP", headers=request_headers)
tree = html.fromstring(webpage.content)
raw_img=tree.xpath('//*[@class="_2rDnao"]//img')

编辑:添加 python 代码

【问题讨论】:

  • 其余代码在哪里?你在用硒吗?
  • @QHarr 我已经添加了代码。

标签: python-3.x xpath web-scraping


【解决方案1】:

图片url也位于底部包含json的脚本中。

import requests
from bs4 import BeautifulSoup
import json

r = requests.get('https://www.flipkart.com/f-d-f550x-56-w-bluetooth-home-theatre/p/itmea2aspwcaxuaz?pid=ACCEA2ASHNDGV4DP')
soup = BeautifulSoup(r.text, 'html.parser')

script = soup.find(id='jsonLD')
json = json.loads(script.text)
for obj in json:
    if obj['@type'] == 'Product':
        url = obj['image']

print(url)

输出为http://rukmini1.flixcart.com/image/128/128/speaker/home-audio-speaker/4/d/p/f-d-a550x-original-imaea2ftzywquzrz.jpeg?q=70

【讨论】:

  • 不使用美汤我们还有其他选择吗?
  • 我在网站上找不到收集这些数据的任何 api,所以这是我能想到的最简单的解决方案。你总是可以使用 Selenium (其他答案),但这更麻烦,beautifulsoup 更容​​易。您所要做的就是在命令行中运行 pip install requestspip install bs4 以使该解决方案生效。
【解决方案2】:

即使通过 xpath 检查页面,我也看不到相同的尺寸。如果您不介意大小的一些变化(您可以随时调整尺寸),那么从 response.text 中正则表达式很容易

import requests, re

r = requests.get('https://www.flipkart.com/f-d-f550x-56-w-bluetooth-home-theatre/p/itmea2aspwcaxuaz?pid=ACCEA2ASHNDGV4DP')
p = re.compile(r'image":"(.*?)"')
print(p.findall(r.text)[0])

【讨论】:

    【解决方案3】:

    注意:此解决方案基于 Selenium xpath 是正确的。您必须使用 get_attribute 来获取文本。

    imgElement = driver.find_element_by_xpath("//*[@class='_2rDnao']//img")
    print(imgElement.get_attribute('src'))
    

    输出是,

    https://rukminim1.flixcart.com/image/416/416/speaker/home-audio-speaker/4/d/p/f-d-a550x-original-imaea2ftzywquzrz.jpeg?q=70

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-21
      • 2020-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-11
      • 1970-01-01
      相关资源
      最近更新 更多