我尝试了这段代码,但它不起作用。我搜索了所有资源。 URL 重定向似乎是由 JavaScript 处理的,没有
<a>
标签或 onclick 事件。
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
def SCHLproject(query):
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--disable-gpu")
driver = webdriver.Chrome(options=chrome_options)
url = f"https://www.truemeds.in/search/{str(query)}"
print(driver.page)
driver.get(url)
ele = driver.find_element(By.CLASS_NAME, "sc-452fc789-2 eIXiYR")
ele.click()
print(driver.current_url)
SCHLproject("naxdom")
确实,在您的案例中,某些 DOM 元素中未指定重定向 URL。
点击元素时,JS 从“https://services.tmmumbai.in/BotService/fetchUrl?productCode=XXX”获取。
您必须传递所需产品的代码而不是“XXX”。
但 DOM 中也没有指定产品代码。
看起来你可以从img src中提取它。
这是对我有用的代码,但需要在不同的输入上进行测试:
import re
import requests
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
def get_product_url(product_code):
r = requests.get(f"https://services.tmmumbai.in/BotService/fetchUrl?productCode={product_code}")
return r.json()["URL"]
def SCHLproject(driver, query, timeout=10):
driver.get(f"https://www.truemeds.in/search/{query}")
els = WebDriverWait(driver, timeout).until(
EC.visibility_of_all_elements_located((By.XPATH, "//p/following-sibling::div//div/img"))
)
urls = []
for el in els:
src = el.get_attribute("src")
re_res = re.search(r"ProductImage/([^/]+)/", src)
if re_res:
product_code = re_res.group(1)
else:
raise RuntimeError(f"Product code is not found in the img src: {src}")
urls.append(get_product_url(product_code))
return urls
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--disable-gpu")
driver = webdriver.Chrome(options=chrome_options)
try:
print(SCHLproject(driver, "naxdom"))
finally:
driver.quit()
请注意,我已将定位器更改为 XPath,使用“sc-452fc789-2 eIXiYR”等类有时可能会很棘手,因为此类 ID 通常由前端框架自动生成,这意味着它们可能很容易更改。
建议的 XPath 也不能称为“可靠”定位器,但它绝对比动态类更好。
提供的代码返回所显示产品的端点列表(不包括网站地址本身)