我正在尝试使用Beautiful Soup和Python来从网站上获取PHP值。
我还尝试使用lxml库。
有没有办法这样做?或者我应该使用不同的东西?提前谢谢。
遵循的步骤
XPATH:
//*[@id="monetary_offer_content"]/div[1]/div[2]/div/div[1]/h3/span
CSS选择器
monetary_offer_content > div.monetary_offer > div.offers.clear > div > div.clearfix > h3 > span
HTML:
<span data-oldoffer="">320</span>
将整个HTML页面输出到.txt文件然后点击元素名称:
| => cat text.txt | grep data-oldoffer
<h3>$<span data-oldoffer><%= value['offer'] %></span></h3>
<h3>$<span data-oldoffer><%= value['offer'] %></span></h3>
Python代码
from bs4 import BeautifulSoup
import urllib2
url="http://website_url.com"
page=urllib2.urlopen(url)
soup = BeautifulSoup(page.read(), "lxml")
print(soup)
答案 0 :(得分:1)
看起来该值是通过浏览器中的javascript动态设置的。您使用urllib2
下载的页面源仅包含初始HTML。
您可以通过selenium
启动并控制真实浏览器,示例:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
url = "http://website_url.com"
driver = webdriver.Firefox()
wait = WebDriverWait(driver, 10)
driver.get(url)
elm = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#monetary_offer_content > div.monetary_offer > div.offers.clear > div > div.clearfix > h3 > span")))
print(elm.text)
driver.close()