【问题标题】:html content changes when using beautifulSoup使用 beautifulSoup 时 html 内容发生变化
【发布时间】:2018-08-30 14:48:59
【问题描述】:

我正在尝试从html块中提取src的属性值,html块是:

<img class="product-image first-image" src="https://cache.net-a-porter.com/images/products/1083507/1083507_in_pp.jpg">

我的代码是:

import requests
import json
from bs4 import BeautifulSoup
import re
headers = {'User-agent': 'Mozilla/5.0'}
url = 'https://www.net-a-porter.com/us/en/product/1083507/maje/layered-plaid-twill-and-stretch-cotton-jersey-top'
page = requests.get(url, headers=headers)
soup = BeautifulSoup(page.content, 'html.parser')
if url.find('net-a-porter')!=-1 :
  i = soup.find_all('img', class_="product-image first-image")[0]["src"]
  print i

我得到的结果:

//cache.net-a-porter.com/images/products/1083507/1083507_in_xs.jpg

但我想得到原始 html 中的内容,应该是:

https://cache.net-aporter.com/images/products/1083507/1083507_in_pp.jpg

我的结果与原来的 src 值不同,http: 消失了,1083507_in_pp 更改为 1083507_in_xs。我不知道为什么会这样,有谁知道如何解决这个问题?谢谢!

【问题讨论】:

  • 解决什么?期望的结果是什么? :)
  • 想获取src中的jpg url
  • 尝试使用字符串连接将 src 值附加到 url 值
  • 但它们并不相同。
  • ?当然它们不一样,如果它们相同,你为什么要附上它们

标签: python html beautifulsoup python-requests web-crawler


【解决方案1】:

您已经很接近了,但是,您需要从内置的attrs 密钥访问"src" 密钥:

if url.find('net-a-porter')!=-1 :
  i = soup.find_all('img', class_="product-image first-image")[0]
  print i['src']

【讨论】:

  • 对不起,这不是我想问的,已经编辑了我的问题,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-20
  • 2021-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多