我必須requests_html用于 JavaScript 內容。代碼:
<td class="text-left worker-col truncated"><a href="/account/0x58e0ff2eb3addd3ce75cc3fbdac3ac3f4e21fa/38-G1x" style="color:red">38-G1</a></td>
我想找到所有帶有紅色的名稱(在本例中為 38-G1)。我想通過 搜索它們style="color:red"。這可能requests_html嗎?我怎么能做到這一點?
uj5u.com熱心網友回復:
我確實將 html session 和 selenium 與 bs4 一起使用。Selenium 作業正常,但 html 會話無法呈現 js。
硒代碼。(成功)
from bs4 import BeautifulSoup
import time
from selenium import webdriver
driver = webdriver.Chrome('chromedriver.exe')
url = URL
driver.get(url)
time.sleep(8)
soup = BeautifulSoup(driver.page_source, 'html.parser')
for t in soup.select('table.table.table-bordered.table-hover.table-responsive tr'):
txt= t.select_one('td:nth-child(2) > a')
text= txt.text if txt else None
print(text)
輸出:
38-G15
47_G15_2
47-G1
49-O15
90_GGX
91_ASF
105_MGPM_3
112-GG3
121-APRO
188-MGPM1
198-AP
248_MGPM_1
262-GUD
265_ASF
302-AD
355-GUD.2
Rig_3471855
rigEdge
107_MGPM_3
None
None
帶有 html 會話的代碼(不呈現 js)
from bs4 import BeautifulSoup
from requests_html import HTMLSession
session = HTMLSession()
response = session.get(URL)
soup = BeautifulSoup(response.content, 'html.parser')
for t in soup.select('table.table.table-bordered.table-hover.table-responsive tr'):
txt= t.select_one('td:nth-child(2) > a')
text= txt.text if txt else None
print(text)
uj5u.com熱心網友回復:
編輯:在這種情況下,樣式是在頁面加載后由 javascript 添加的,因此您必須等待整個頁面加載后再抓取它,所以 Selenium 是要走的路。
你可以這樣抓取頁面,就像 Fazlul 那樣:
from bs4 import BeautifulSoup as bs
import time
from selenium import webdriver
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
driver = webdriver.Chrome('chromedriver',chrome_options=chrome_options)
driver.get("URL")
time.sleep(5)
html = bs(driver.page_source, 'html.parser')
那么你可以使用 CSS 通配符選擇器,然后列印出它們的innerText:
anchors = html.select('a[style*="color:red"]')
print([a.text for a in anchors])
或者
<a>如果它們具有該屬性,您可以找到所有標簽并將它們放入串列中。
anchors = html.select('a')
names = []
for a in anchors:
if 'style' in a.attrs and "color:red" in a.attrs['style']:
names.append(a.text)
編輯:我看到其他用戶為您提供了 BeautifulSoup 的解決方案,我想補充一點,如果您不熟悉網頁抓取,但您打算了解更多資訊,我還建議您學習使用 BeautifulSoup。它不僅功能更強大,而且用戶群也更大,因此更容易為您的問題找到解決方案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/369467.html
標籤:javascript Python 网页抓取 找 python-请求-html
