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

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)

"""以上的代码都是用于导入库,和获取url而写的,可以先忽略不看,
看下面的代码,我是打算通过urls遍历得到每个url的数据,可是得出来都是重复的
"""

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))

  • 写回答

2条回答 默认 最新

  • cjh4312 2023-01-20 21:33
    关注

    窗口切换不对,要切换到最新打开窗口
    driver.switch_to.window(driver.window_handles[-1])

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

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

悬赏问题

  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗