获取猫眼电影所有城市信息
做一个关于猫眼电影的爬虫要查看全国的分布,就必须第一步先拿到所有的影院所在城市信息。这个下拉列表不算太好解决,如果只是用requests的话,这里用selenium。
更新:从js中获取 https://blog.csdn.net/qq_42776455/article/details/86491393
代码解释
主要用到的ActionChains,里面储存了一系列动作如:鼠标移动,鼠标点按,键盘操作,文本操作等。当ActionChains对象调用perform()时,这些操作会被先储存在一个队列中,队列中的操作会被按顺序执行,执行后队列被清空。
典型用法,可以用来破解滑动的验证码识别。
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from lxml import etree
driver = webdriver.PhantomJS()
Wait = WebDriverWait(driver,5)
def get_cities():
driver.get('https://maoyan.com/')
try:
actions = ActionChains(driver)
# city_tag = driver.find_element_by_xpath('//div[@class="city-name"]')
city_tag = Wait.until(
EC.presence_of_element_located((By.XPATH,'//div[@class="city-name"]'))
)
actions.click(city_tag).perform()
html = driver.page_source
finally:
driver.quit()
xpath_parser = etree.HTML(html)
city_list = xpath_parser.xpath('//div[@class="city-list"]//a[@class="js-city-name"]/text()')
return city_list
print(get_cities())
结果从A开始,当然后面可能会用到每个城市的city_id,xpath表达式自己添加就可以了。