函数Python.strip()给出了带有HTML(BeautifulSoup)的变量的错误

函数Python.strip()给出了带有HTML(BeautifulSoup)的变量的错误,python,beautifulsoup,Python,Beautifulsoup,这段代码从amazon获取产品名称。我想去掉这个变量,它包含HTML的空白 span = soup.find("span", id="productTitle") print(span.strip()) 但它给了我这个错误 Traceback (most recent call last): File "C:/Users/avensis/Desktop/Projects/AmazonScraper/Scraper.py", lin

这段代码从amazon获取产品名称。我想去掉这个变量,它包含HTML的空白

span = soup.find("span", id="productTitle")
print(span.strip())
但它给了我这个错误

Traceback (most recent call last):
  File "C:/Users/avensis/Desktop/Projects/AmazonScraper/Scraper.py", line 17, in <module>
    print(span.strip())
TypeError: 'NoneType' object is not callable
使用
.get_text()
方法:

span.get_text().replace("\n", "")

'Pingu - Mug | 300 ml | Ceramic | Gift Box | 11 x 8.5 x 8.5 cm'
使用
.get_text()
方法:

span.get_text().replace("\n", "")

'Pingu - Mug | 300 ml | Ceramic | Gift Box | 11 x 8.5 x 8.5 cm'

我想这就是你想要做的:

from bs4 import BeautifulSoup
import requests
import html5lib
import random

url = 'https://www.amazon.co.uk/Pingu-PING2573-Mug/dp/B0764468MD/ref=sr_1_11?dchild=1&keywords=pingu&qid=1595849018' \
      '&sr=8-11 '
headers = {
    "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                  'Chrome/84.0.4147.89 Safari/537.36'}
page = requests.get(url, headers=headers)
soup = BeautifulSoup(page.content, 'html5lib')


span = soup.find("span", id="productTitle")

print(span.get_text(strip=True))
印刷品:

Pingu - Mug | 300 ml | Ceramic | Gift Box | 11 x 8.5 x 8.5 cm

如果它是你要找的,那么它就是你错过的
.get_text(strip=True)
我想这就是你想要做的:

from bs4 import BeautifulSoup
import requests
import html5lib
import random

url = 'https://www.amazon.co.uk/Pingu-PING2573-Mug/dp/B0764468MD/ref=sr_1_11?dchild=1&keywords=pingu&qid=1595849018' \
      '&sr=8-11 '
headers = {
    "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                  'Chrome/84.0.4147.89 Safari/537.36'}
page = requests.get(url, headers=headers)
soup = BeautifulSoup(page.content, 'html5lib')


span = soup.find("span", id="productTitle")

print(span.get_text(strip=True))
印刷品:

Pingu - Mug | 300 ml | Ceramic | Gift Box | 11 x 8.5 x 8.5 cm

如果它是你要找的,那么它就是你错过的
.get_text(strip=True)
None
,因为beautiful soup没有找到
id=“productTitle”
span
。这就是导致错误的原因。span是
None
,因为Beauty soup没有找到
span
id=“productTitle”
。这就是给你带来错误的原因。清楚而准确地说明我在寻找什么!清楚而准确地知道我在找什么!