python - 如何从该网页中抓取文本?

标签 python web-scraping beautifulsoup python-requests python-3.7

我正在尝试抓取此 HTML 标题

<h2 id="p89" data-pid="89"><span id="page77" class="pageNum" data-no="77" data-before-text="77"></span>Tuesday, July&nbsp;30</h2>

来自此网站:https://wol.jw.org/en/wol/h/r1/lp-e

我的代码:

from bs4 import BeautifulSoup
import requests

url = requests.get('https://wol.jw.org/en/wol/h/r1/lp-e').text

soup = BeautifulSoup(url, 'lxml')

textodiario = soup.find('header')

dia = textodiario.h2.text
print(dia)

它应该返回今天的日期,但它返回过去的一天:7 月 24 日星期三

最佳答案

目前我没有电脑可供测试,请仔细检查是否存在可能的错误。

您需要chromedriver for your platform too ,将其放在脚本的同一文件夹中。

我的想法是使用 selenium 获取 HTML,然后解析它:

import time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

url = "https://wol.jw.org/en/wol/h/r1/lp-e"
options = Options()
options.add_argument('--headless')
options.add_argument('--disable-gpu')
driver = webdriver.Chrome(chrome_options=options)
driver.get(url)
time.sleep(3)
page = driver.page_source
driver.quit()
soup = BeautifulSoup(page, 'html.parser')
textodiario = soup.find('header')
dia = textodiario.h2.text
print(dia)

关于python - 如何从该网页中抓取文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57271349/

相关文章:

python - sp_execute_external_script 内存变量中的 Python 以加快进程

python - 从特定表格元素中抓取特定文本时返回错误数据

python - 网络抓取逐渐变慢并最终停止的可能原因有哪些?

Python BeautifulSoup findAll 通过 "class"属性

python - 使用 Python 和 Beautiful Soup 从 .html 文件中提取文本,删除 HTML,然后写入文本文件

python - 如何从自定义数据格式创建 scipy 数组?

python - 尝试将 Python Pandas 中带有字符串的列转换为 Float 时出错

python - 如何从 requests.get() 获取更多标签

python - Docker flask 应用程序环境变量

java - 如何使用JAVA inputStream从HTML代码中抓取汉字?