【发布时间】:2016-12-27 00:32:12
【问题描述】:
我创建了一个基本程序来尝试使用 BeautifulSoup 4 为我的外部 IP 地址抓取网站。虽然,我的程序不断收到属性错误,因为它无法获取 div 类的字符串或其他任何东西。它会显示为特定的 div 类不存在,因此无法对其进行爬网。我确实知道它存在,即使它说它不存在。有谁知道怎么回事?
这是我的代码:
import requests, sys, io
from html.parser import HTMLParser
from bs4 import BeautifulSoup
url = "https://www.iplocation.net/find-ip-address"
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, "cp437", "backslashreplace")
sourcecode = requests.get(url)
plaintext = sourcecode.text
soup = BeautifulSoup(plaintext, "html.parser")
tag = soup.find("span", {"style": "font-weight: bold; color:green;"})
print(tag)
ip = tag.string
print(ip)
【问题讨论】:
-
该网站上没有一个
span元素。 -
当我检查网站的元素时,它说
<span style="font-weight: bold; color:green;">00.00.000.00</span> -
@Rawing 是
<p style="font-size:1.4em;" align="center">Your IP Address is <span style="font-weight: bold; color:green;">00.00.000.00</span>.</p>的子元素 -
你说得对,我又试了一次,但加载方式不同。不知道为什么网站随机更改。
-
我在呈现的页面上看到它......它可能是由 javascript 生成的。在使用 beautifulsoup 之前,我会使用 selenium 而不是请求来加载页面。
标签: python python-3.x beautifulsoup ip web-crawler