【问题标题】:Selenium & Python, get child of dynamic src while using XPATHsSelenium 和 Python,在使用 XPATH 时获取动态 src 的子节点
【发布时间】:2019-04-03 00:33:39
【问题描述】:

我有一些要抓取的 html。

<div class="prw_rup prw_common_static_map_no_style staticMap" data-prwidget-name="common_static_map_no_style" data-prwidget-init="handlers">
    <div class="prv_map clickable" onclick="requireCallLast('ta/maps/opener', 'open', 2, null, null,{customFilters: []})">
         <img width="310" style="width:310px;height:270px;" id="lazyload_-1295083988_4" height="270" src="https://trip-raster.citymaps.io/staticmap?scale=2&amp;zoom=18&amp;size=310x270&amp;language=en&amp;center=32.769936,-117.252693&amp;markers=icon:http%3A%2F%2Fc1.tacdn.com%2Fimg2%2Fmaps%2Ficons%2Fpin_v2_CurrentCenter.png|32.769936,-117.25269&amp;markers=icon:http%3A%2F%2Fc1.tacdn.com%2Fimg2%2Fmaps%2Ficons%2Fpin_lg_Restaurant.png|32.769936,-117.25269|32.770027,-117.25272&amp;markers=icon:http%3A%2F%2Fc1.tacdn.com%2Fimg2%2Fmaps%2Ficons%2Fpin_lg_ThingToDo.png|32.77055,-117.25273|32.770683,-117.251884|32.770664,-117.25131">
    </div>
</div>

如何检索子 div 的 src?意思是,我想将 url 作为字符串返回。

到目前为止,我最接近它的是。

try:
    mappa = driver.find_element_by_xpath("""//*[@id="taplc_location_detail_overview_restaurant_0"]/div[1]/div[2]/div[1]/div""") # .get_attribute("src")
    print(mappa, "this is mappa")
    child_mappa = mappa.find_element_by_xpath('.//*').get_attribute("src")
    print(child_mappa)

产生:

$ <selenium.webdriver.remote.webelement.WebElement (session="4c6acf0a93bc9c184a351ddbc2180977", element="0.5263477154236882-1")> 
$ https://static.tacdn.com/img2/x.gif

由于 id 是动态的,我不能用它来获取 xpath。因为 xpath 与该 ID 相关。另外,为什么那个 src 会改变?

如何获得该 src?

【问题讨论】:

  • 嗯,可能我对child的理解还不完整。

标签: python selenium xpath dynamic src


【解决方案1】:

所以,这有点不稳定,但我设法使用正则表达式得到它。我没有用 selenium 抓取它,而是阅读了所有 html,用正则表达式查找 url 并将其拆分到我需要的地方。

它不干净,但它有效。

    driver.get(url)
    innerHTML = driver.execute_script("return document.body.innerHTML")
    print(type(innerHTML))

    try:
        urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', innerHTML)
        #print(urls)
        for page_url in urls:
            if 'staticmap?scale=' in page_url:
                map_click = page_url.split('language=en&center=')[1].split('&markers=icon:http')[0]
                lat, long = map_click.split(',')
                break
    except:
        lat, long = None, None

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-25
    • 2016-05-04
    • 2015-03-30
    相关资源
    最近更新 更多