使用 Selenium 和 BeautifulSoap,我正在嘗試抓取網頁。一般來說,這作業正常。請在下面找到代碼。
在此頁面上列出了一些類別。深度為 4 級。在每個級別上,我有 20 個專案/鏈接。
我的問題是:在回圈中打開和處理這些鏈接的最有效方法是什么?
import sys
sys.path.insert(0,'/usr/lib/chromium-browser/chromedriver')
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from bs4 import BeautifulSoup
import time
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
wd = webdriver.Chrome('chromedriver',options=options)
wd.get("url")
source = wd.page_source
soup = BeautifulSoup(source, "html.parser")
items = soup.select('ul[data-card-id="tree-list0972"]')
for item in items:
ul = item.find('ul')
for li in ul:
print(li.a.get('href') ',' li.a.text)
cats = webdriver.Chrome('chromedriver',options=options)
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
# Here i do need to open the link from the url list (3 levels deep)
cats.get(h domain li.a.get('href'))
WebDriverWait(webdriver, timeout=3)
cats.close
wd.close
uj5u.com熱心網友回復:
我可能會嘗試在這樣的結構中實作沒有 BeautifulSoap 的用例:
1. 創建網路驅動
wd = webdriver.Chrome('chromedriver',options=options)
2.打開“主”網頁
wd.get("url")
3.獲取所有元素
elements = wd.find_elements_by_css_selector('ul[data-card-id="..."])
4.獲取每個元素的url
pages = []
for element in elements:
pages.append(element.get_attribute('href')
5.處理每一頁
for page in pages:
wd.get(page)
# ...
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/355900.html
上一篇:迭代單選按鈕并單擊
