簡體   English   中英

使用 Selenium/BeautifulSoup 在 HTML 個元素中查找模式

[英]Find pattern in HTML elements with Selenium/BeautifulSoup

我有這個 html,我正試圖從沖浪熱中刮掉

     <div class="event-round">
           <div id="heat-85940" class="new-heat  new-heat--status-completed new-heat--athletes-4">
           <div id="heat-85941" class="new-heat  new-heat--status-completed new-heat--athletes-4">
           <div id="heat-85942" class="new-heat  new-heat--status-completed new-heat--athletes-4">
           <div id="heat-85943" class="new-heat  new-heat--status-completed new-heat--athletes-4">
     <div>

我創建了一個循環來收集每一頁上的熱度,但是因為熱度 ID 在每一頁上都在變化(即並不總是從 85940 開始),我只能獲得 1 頁的價值,而無需手動更改我循環的范圍。

對於一頁,我的代碼如下所示:

heat_count = len(driver.find_elements(By.CLASS_NAME, 'new-heat-hd-name').text)

for h in range(heat_count):
    for i in range(4):
        name = driver.find_element(By.XPATH, f'//*[@id="heat-8594{h}"]/div/div[2]/div[{i + 1}]/div[1]/div[1]/div/div[2]/div[1]/span').text

我正在尋找一種在 html 中搜索以查找heat-85940 ,然后從那里開始,而不是為每個頁面手動查找它。

你可以試試這個:

這里我只寫XPath的開始部分——即如何處理動態值'id="heat-85940"',請填寫剩余的XPath,因為你沒有發布URL和完整的HTML源。

driver.find_element(By.XPATH, ".//*[starts-with(@id,'heat-')]...<remaining XPath until the element>")

要么

driver.find_element(By.XPATH, ".//*[starts-with(@id,'heat-8594')]...<remaining XPath until the element>")

你可以嘗試類似的東西

# heats = driver.find_elements(By.XPATH, '//*[starts-with(@id,"heat-")]')
heats = driver.find_elements(By.CSS_SELECTOR, '*[id^="heat-"]')
for heat in heats:
    names = heat.find_elements(By.XPATH, '/div/div[2]/div/div[1]/div[1]/div/div[2]/div[1]/span')
    for n in names[:4]:
        name = n.text

要么

# heats = driver.find_elements(By.XPATH, '//*[starts-with(@id,"heat-")]')
heats = driver.find_elements(By.CSS_SELECTOR, '*[id^="heat-"]')
for heat in heats:
    for i in range(4):
        name = heat.find_element(By.XPATH, f'/div/div[2]/div[{i + 1}]/div[1]/div[1]/div/div[2]/div[1]/span').text

(如果沒有更多您的 html,我無法測試這些,所以我對它們中的任何一個都不太有信心。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM