我正在尝试解析来自Dailyfx.com的外汇EurUsd值。我可以在那里看到我想要的值,但是当我抓取/解析它时,我在txt-file中得到了值"--“。
这里是dailyfx.com: data-value="1.18218“

我使用的代码如下:
import urllib.request
opener=urllib.request.build_opener()
opener.addheaders=[('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/36.0.1941.0 Safari/537.36')]
urllib.request.install_opener(opener)
req = urllib.request.Request("https://www.dailyfx.com/eur-usd", headers={"User-Agent":
"Chrome"})
res = urllib.request.urlopen(req)
data=res.read()
with open("test.txt", "w") as f:
f.write(str(data))
f.close()当我打开文件(test.txt)时,我会发现空值:
data-value=“-”
当我期望看到时,data-value="1.18218“。

发布于 2020-11-17 07:15:08
该网站是动态加载的,因此urlib不支持它。我们可以使用Selenium作为抓取页面的替代方案。
使用:pip install selenium安装它。
从here下载正确的ChromeDriver。
from time import sleep
from selenium import webdriver
from bs4 import BeautifulSoup
URL = "https://www.dailyfx.com/eur-usd"
driver = webdriver.Chrome(r"C:\path\to\chromedriver.exe")
driver.get(URL)
# Wait for the page to fully render
sleep(5)
soup = BeautifulSoup(driver.page_source, "html.parser")
with open("output.txt", "w", encoding="utf-8") as f:
f.write(soup.prettify())
driver.quit()注意:由于您使用上下文管理器来写入该文件,因此没有理由使用f.close()关闭它,它将在退出with(...)块后自动关闭。
https://stackoverflow.com/questions/64859445
复制相似问题