如何检查页面上是否存在 element/tag

How to check if a element/tag exists on page

我正在尝试检查网页上是否存在名称为“message message-information”的 class 元素,除非我尝试时得到一个 AttributeError:'NoneType'.

base_name = "GeForce RTX 3070 Ti"
url = "https://www.evga.com/products/product.aspx?pn=08G-P5-3797-KL"

headers = {"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'}

site = requests.get(url, headers=headers)
soup = BeautifulSoup(site.content, 'html.parser')

stock_info = soup.find(class_="message message-information").get_text() # The ID of the stock element
   
# Check if the element is on the page, if not then say there is stock
if stock_info is None:
    # If the element exists
    tools.nogpustock(base_name)
else:
    # if the element does not exist
    tools.hasgpustock(base_name)

只是不要调用 .get_text(),如果标签不存在,soup.find(class_="message message-information") 返回的值将是 None 并且调用 None.get_text() 将触发 AttributeError: 'NoneType'

你的代码可能像

base_name = "GeForce RTX 3070 Ti"
url = "https://www.evga.com/products/product.aspx?pn=08G-P5-3797-KL"

headers = {"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'}

site = requests.get(url, headers=headers)
soup = BeautifulSoup(site.content, 'html.parser')

stock_info_tag = soup.find(class_="message message-information") # The ID of the stock element
   
# Check if the element is on the page, if not then say there is stock
if stock_info is None:
    # If the element exists
    tools.nogpustock(base_name)
else:
    # if the element does not exist
    tools.hasgpustock(base_name)
    stock_info = stock_info_tag.get_text()