如何使用Selenium(python)在页面上随机点击以及如何放大页面?

时间:2017-01-04 18:10:51

标签: python selenium selenium-webdriver webdriver

我想知道是否有人使用selenium在给定页面上的指定区域内随机点击。

此外,有没有人知道如何缩放到页面的指定区域。例如,页面是x乘y,但我想放大到原始页面中特定区域的坐标区域,(0,1 / 4x)乘以(0,1 / 4 y)或(1 / 4 x,2/4 x)乘以(1/4 y,2/4 y),这一点是当一个放大到页面的某个区域时内容发生变化。

我头脑中的代码如下:

For i in x:
  Page = driver.zoom((x1, x2), (y1, y2)) # where x1 to x2 is the horizontal of the page and the y1 to y2 are the vertical dimensions of where I want to look
  x_coord = random.uniform(x1, x2) #randomly pulling x coord
  y_coord = random.uniform(y1, y2) #randomly pulling y coord
  webdriver.click(x_coord, y_coord) 
  webdriver.read_page()

有谁知道如何实施?

1 个答案:

答案 0 :(得分:0)

最好在查找动态项目时使用css选择器,因为它最不可能更改。



driver = webdriver.Firefox()
driver.get('https://www.youtube.com/watch?v=hhR3DwzV2eA')


# store the current url in a variable
current_page = driver.current_url

# create an infinite loop
while True:
    try:
        # find element using css selector
        links = driver.find_elements_by_css_selector('.content-link.spf-link.yt-uix-sessionlink.spf-link')

        # create a list and chose a random link
        l = links[randint(0, len(links) - 1)]

        # click link
        l.click()

        # check link
        new_page = driver.current_url

        # if link is the same, keep looping
        if new_page == current_page:
            continue
        else:
            # break loop if you are in a new url
            break
    except:
        continue




作为一个例子,我使用了YT视频。假设你想点击右侧的推荐视频,那么它有一个独特的css选择器用于这些链接。

你想要进行无限循环的原因是b / c,当你制作一个元素列表时,由于某种原因,python不能很好地表达存储的元素。除了' b / c你会得到Timeout Errors等等,你想强迫它点击随机链接。