首頁  >  問答  >  主體

網路爬蟲過程中無法定位HTML元素。該元素在網站檢查工具中可見

我正在嘗試從此URL中爬取所有表格的標題:https://www.nature.com/articles/s41586-023-06192-4

我可以在網站上找到這個HTML元素:

<b id="Tab1" data-test="table-caption">Table 1 Calculated Ct–M–Ct angles</b>

我無法爬取這個標題,因為找不到它。 即使我將HTML腳本列印到控制台,也找不到這個元素。

我使用以下程式碼列印HTML腳本:

from requests_html import HTMLSession
from bs4 import BeautifulSoup

url = 'https://www.nature.com/articles/s41586-023-06192-4'

session = HTMLSession()
response = session.get(url)

response.html.render()

soup = BeautifulSoup(response.html.raw_html.decode('utf-8'), 'html.parser')
print(soup.prettify())

使用BeautifulSoup的爬取函數:

def get_tables(driver):
    tables = []
    html = driver.page_source
    soup = BeautifulSoup(html, 'html.parser')

    for i in range(1, 11):
        try:
            table_caption = soup.find('b', {'id': f'Tab{i}', 'data-test': 'table-caption'})
            table_text = table_caption.text if table_caption else "Not Available"
            if table_text != "Not Available":
                print(f"找到表格{i}:{table_text}")
            else:
                print(f"未找到表格{i}。")
            tables.append(table_text)
        except Exception as e:
            print(f"处理表格{i}时出错:{str(e)}")
            tables.append("Not Available")

    return tables

使用Selenium的爬取函數:

def get_tables(driver):
    tables = []

    for i in range(1, 11):
        try:
            table_caption = driver.find_element_by_css_selector(f'b#Tab{i}[data-test="table-caption"]')
            table_text = table_caption.text if table_caption else "Not Available"
            if table_text != "Not Available":
                print(f"找到表格{i}:{table_text}")
            else:
                print(f"未找到表格{i}。")
            tables.append(table_text)
        except Exception as e:
            print(f"处理表格{i}时出错:{str(e)}")
            tables.append("Not Available")

    return tables

我嘗試使用Selenium和BeautifulSoup來爬取網站。 我已經檢查了iframe。 我延遲了提取操作40秒,以確保頁面完全加載。 即使是GPT4也無法解決這個問題。

P粉225961749P粉225961749395 天前554

全部回覆(1)我來回復

  • P粉920485285

    P粉9204852852023-09-20 10:49:02

    所以你使用的程式碼看起來沒問題,我想到的問題是,網站可能是透過JavaScript或某個XHR呼叫來載入你要爬取的那個元素,因此當你使用requests函式庫發送請求時,它無法獲取到那個元素。

    解決這個問題的方法是,試著使用Selenium,用selenium開啟網站,然後將頁面原始碼載入到bs4中,這樣你的程式碼就能正常運作了。

    注意:當整個網站載入完畢後,將頁面原始碼載入到bs4。你還需要使用selenium建立一個登入功能,因為這個網站需要登入才能查看內容。

    回覆
    0
  • 取消回覆