如何从该网页上抓取文字?

时间:2019-07-30 12:10:44

标签: 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)

它应该今天返回我,但它返回了过去的一天:Wednesday, July 24

4 个答案:

答案 0 :(得分:2)

目前我没有要测试的PC,请仔细检查是否存在错误。

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

我的想法是使用硒来获取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)

答案 1 :(得分:0)

数据正在异步加载,并且div的内容正在更改。您需要一个与bs4一起运行的Selenium Web驱动程序。 enter image description here

答案 2 :(得分:0)

我实际上尝试了您的代码,网站/代码捕获数据的方式肯定存在问题。因为当我将整个URL文本通过管道传输到7月的grep时,它给出了:

Wednesday, July 24
<h2 id="p71" data-pid="71"><span id="page75" class="pageNum" data-no="75" data-before-text="75"></span>Wednesday, July 24</h2>
<h2 id="p74" data-pid="74">Thursday, July 25</h2>
<h2 id="p77" data-pid="77">Friday, July 26</h2>

如果我不得不猜测,他们在h2下可能保留多个日期的事实 并没有帮助,但是我在网络抓取方面的经验几乎为零。而且,如果您注意到,7月30日甚至还没到那儿,这意味着沿线某个地方的数据变得很奇怪(正如LazyCoder指出的那样)。

希望Selenium可以解决您的问题。

答案 3 :(得分:0)

转到NetWork标签,您将获得链接。

https://wol.jw.org/wol/dt/r1/lp-e/2019/7/30

这是代码。

from bs4 import BeautifulSoup
headers = {'User-Agent':
        'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}
session = requests.Session()
response = session.get('https://wol.jw.org/wol/dt/r1/lp-e/2019/7/30',headers=headers)
result=response.json()
data=result['items'][0]['content']
soup=BeautifulSoup(data,'html.parser')
print(soup.select_one('h2').text)

输出:

Tuesday, July 30