我试图刮一些网页,通过谷歌搜索访问他们,我需要添加一些限制词列表。
让我们说,在Google搜索中Python的4个顶级结果是:
然后,我想打开第一个结果,它不包含搜索描述和/或链接中的".org“、"wikipedia”之类的单词(在本例中,脚本将打开w3schools)。
我试图用不同的选择器完成工作,并获得整个谷歌搜索页面文档,但到目前为止,没有取得任何积极的结果:
search = driver.find_element_by_name('q')
search.send_keys("Gran Hotel La Florida G.L Monumento")
search.send_keys(Keys.RETURN) # hit return after you enter search text time.sleep(5)
driver.find_element_by_class_name('LC20lb').click()
这将打开第一个非广告结果。
发布于 2019-04-28 12:19:55
您可以更新选择器以单击所需的链接:
driver.find_element_by_xpath('//h3[@class="LC20lb" and not(contains(text(), "org")) and not(contains(text(), "wikipedia"))]').click()
这将排除包含子字符串"org"
和"wikipedia"
的结果。
发布于 2019-04-28 14:35:26
CSS:
可能类似这样的内容,它排除了基于href
的href (也限制了以http开头的href,并删除了类.fl
的href)。:not
伪类被传递了一个条件列表--在本例中,大部分是子字符串,以排除via包含操作符。
.r [href^=http]:not(.fl,[href*=\.org],[href*=wikipedia])
下面的测试用例测试了一些不同国家的Google搜索
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup as bs
d = webdriver.Chrome()
d.get('https://www.google.com/')
d.find_element_by_css_selector('[title=Search]').send_keys('python')
WebDriverWait(d, 5).until(EC.element_to_be_clickable((By.CSS_SELECTOR, '[type=submit]'))).click()
WebDriverWait(d,10).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,'.r')))
soup = bs(d.page_source, 'lxml')
links = [link['href'] for link in soup.select('.r [href^=http]:not(.fl,[href*=\.org],[href*=wikipedia])')]
print(links)
https://stackoverflow.com/questions/55890032
复制相似问题