白兔糖糖 2023-01-20 19:50 采纳率: 75%
浏览 33
已结题

selenium切换窗口

如下为一段模拟浏览器爬虫代码,我有15个不一样的url,但all_content 获取的内容是一样的,重复的。我不知道出了什么问题

import random    
from selenium import webdriver
from lxml import etree
import json
import time
#import time
driver_path='D:\geckodriver.exe'
driver=webdriver.Firefox(executable_path=driver_path)
url="https://www.lagou.com/wn/jobs?kd=Java&city=%E5%85%A8%E5%9B%BD/"    
driver.get(url)
html=etree.HTML(driver.page_source)
script=html.xpath('//script[@id="__NEXT_DATA__"]/text()')[0]
script=json.loads(script)
props=script.get('props')
pageProps=props.get('pageProps')
initData=pageProps.get('initData')
content=initData.get('content')
positionResult=content.get('positionResult')
result=positionResult.get('result')
results=[]
for result1 in result:
    positionId= result1.get('positionId')
    results.append(positionId)



urls=[]
for result2 in results:        
    url='https://www.lagou.com/wn/jobs/'+str(result2)+'.html'
    urls.append(url)   
    
all_contents=[]
for url in urls:                                 
    driver.execute_script("window.open('{}')".format(url))
    driver.switch_to.window(driver.window_handles[1])
    html = etree.HTML(driver.page_source)
    job=html.xpath('//span/span[@class="position-head-wrap-position-name"]/text()')
    salary=html.xpath('//span/span[@class="salary"]/text()')
    other=html.xpath('//dd[@class="job_request"]/h3//text()')
    others=''
    for i in other:
        i = i.strip()
        if i=="":
            continue
        elif i=="/":
            continue
        elif '/' in i:
            i=i.replace('/','')
        others+=i+' '
    singles=''    
    single=html.xpath('//dd/div[@class="job-detail"]//text()')
    for b in single:
        b = b.strip()
        if b=="":
            continue
        elif b=="/":
            continue
        elif '/' in b:
            b=b.replace('/','')  
        singles+=b
    all_content={"job":job,"salary":salary,"others":others,"singles":singles}
    all_contents.append(all_content)
    print(all_contents)
    time.sleep(random.uniform(2,4))   
    #driver.close()
   # driver.switch_to.window(driver.window_handles[0])
    #time.sleep(random.uniform(2,4))

  • 写回答

3条回答 默认 最新

  • 等黄昏等你来 2023-01-20 21:40
    关注
    driver.switch_to.window(driver.window_handles[1])这句代码,应该是-1才对(-1切换到最新打开的页面视角),你的视角没有切换成功。
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 1月29日
  • 已采纳回答 1月21日
  • 创建了问题 1月20日

悬赏问题

  • ¥15 有什么好的直流步进减速电机42的厂家推荐,保持力矩达到0.3N.M
  • ¥15 IBS个体遗传距离计算
  • ¥15 一道蓝桥杯的题,请问我错在哪里
  • ¥15 关于#android问题,xposed模块找不到so
  • ¥15 UE5.4.2创建C++项目成功,但是编译失败
  • ¥15 华为手机备份nas,airdisk,遇到的空间不足问题。求个详细的解决方案。
  • ¥20 Cknife无法使用
  • ¥15 这个结构体为什么会出错呢?
  • ¥15 ROH绘图及近交系数的计算
  • ¥15 手动下载基因拼接数据库的渠道