【发布时间】:2018-12-30 20:18:12
【问题描述】:
我在 python 中结合 selenium 编写了一个脚本,使用 proxies 来获取导航到 url 时填充的不同链接的文本,如 this one。我想从那里解析的是连接到每个链接的可见文本。
到目前为止,当在其中调用此函数 start_script() 时,我尝试使用的脚本能够生成新的代理。问题是这个网址将我带到了这个redirected link。只有当我继续尝试直到 url 对代理感到满意时,我才能摆脱这种重定向。我当前的脚本只能使用两个新代理尝试两次。
我如何在 get_texts() 函数中使用任何循环,以便它可以继续尝试使用新的代理,直到它解析所需的内容? p>
到目前为止我的尝试:
import requests
import random
from itertools import cycle
from bs4 import BeautifulSoup
from selenium import webdriver
link = 'http://www.google.com/search?q=python'
def get_proxies():
response = requests.get('https://www.us-proxy.org/')
soup = BeautifulSoup(response.text,"lxml")
proxies = [':'.join([item.select_one("td").text,item.select_one("td:nth-of-type(2)").text]) for item in soup.select("table.table tbody tr") if "yes" in item.text]
return proxies
def start_script():
proxies = get_proxies()
random.shuffle(proxies)
proxy = next(cycle(proxies))
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument(f'--proxy-server={proxy}')
driver = webdriver.Chrome(chrome_options=chrome_options)
return driver
def get_texts(url):
driver = start_script()
driver.get(url)
if "index?continue" not in driver.current_url:
for item in [items.text for items in driver.find_elements_by_tag_name("h3")]:
print(item)
else:
get_texts(url)
if __name__ == '__main__':
get_texts(link)
【问题讨论】:
标签: python python-3.x selenium selenium-webdriver web-scraping