代码之家  ›  专栏  ›  技术社区  ›  Gonzalo

使用selenium和类进行web解析

  •  0
  • Gonzalo  · 技术社区  · 7 年前

    我试图解析一个博客中的几个项目,但我无法找到我需要的最后两个项目。

    html是:

            <div class="post">
                <div class="postHeader">
                    <h2 class="postTitle"><span></span><a href="http://website.com" title="cuba and the cameraman">cuba and the cameraman</a></h2>
                    <span class="postMonth" title="2017">Nov</span>
                    <span class="postDay" title="2017">24</span>
                    <div class="postSubTitle"><span class="postCategories"><a href="http://website.com" rel="category tag">TV Shows</a></span></div>
                </div>
                <div class="postContent"><p><a target="_blank" href="https://image.com/test.jpg"><img class="aligncenter" src="https://image.com/test.jpg"/></a>&nbsp;<br />
    n/A<br />
    &nbsp;<br />
    <strong>Links:</strong> <a target='_blank' href='http://www.imdb.com/title/tt7320560/'>IMDB</a><br />
        &nbsp;</p>
    

    我需要的数据是“古巴和摄影师”(代码如下),以及“ https://image.com/test.jpg “url和” http://www.imdb.com/title/tt7320560/ “IMDB链接。

    我只正确解析了网站的所有帖子:

        all_titles = []
        url = 'http://test.com'
        browser.get(url)
        titles = browser.find_elements_by_class_name('postHeader')
        for title in titles:
            link = title.find_element_by_tag_name('a')
            all_titles.append(link.text)
    

    但我无法使用与上面相同的方法(类名)获取图像和imdb链接。 你能支持我吗?谢谢

    1 回复  |  直到 7 年前
        1
  •  1
  •   CtheSky    7 年前

    你需要更准确的搜索,有一个家庭 find_element_by_XX 内置函数,请尝试xpath:

    for post in driver.find_elements_by_xpath('//div[@class="post"]'):
        title = post.find_element_by_xpath('.//h2[@class="postTitle"]//a').text
        img_src = post.find_element_by_xpath('.//div[@class="postContent"]//img').get_attribute('src')
        link = post.find_element_by_xpath('.//div[@class="postContent"]//a[last()]').get_attribute('href')
    

    请记住,您始终可以通过以下方式获取html源代码: driver.page_source 然后用你喜欢的任何工具解析它。