【问题标题】:Webscraping using selenium, beautifulsoup and python使用 selenium、beautifulsoup 和 python 进行网页抓取
【发布时间】:2017-07-31 04:58:07
【问题描述】:

目前正在抓取一个使用 javascript 的房地产网站。我的过程首先为单个列表抓取包含许多不同 href 链接的列表,将这些链接附加到另一个列表,然后按下一步按钮。我这样做直到下一个按钮不再可点击。

我的问题是,在收集所有列表(约 13000 个链接)后,刮板不会移动到打开链接并获取我需要的信息的第二部分。 Selenium 甚至不会打开以移动到链接列表的第一个元素。

这是我的代码:

wait = WebDriverWait(driver, 10)
while True:
    try:
        element = wait.until(EC.element_to_be_clickable((By.LINK_TEXT, 'next')))
        html = driver.page_source
        soup = bs.BeautifulSoup(html,'html.parser')
        table = soup.find(id = 'search_main_div')
        classtitle =  table.find_all('p', class_= 'title')
        for aaa in classtitle:
            hrefsyo =  aaa.find('a', href = True)
            linkstoclick = hrefsyo.get('href')
            houselinklist.append(linkstoclick)
        element.click()
    except:
        pass

在此之后,我有另一个简单的抓取工具,它遍历列表,在 selenium 中打开它们并收集该列表的数据。

for links in houselinklist:
    print(links)
    newwebpage = links
    driver.get(newwebpage)
    html = driver.page_source
    soup = bs.BeautifulSoup(html,'html.parser')
    .
    .
    .
    . more code here

【问题讨论】:

标签: python selenium web-scraping beautifulsoup


【解决方案1】:

问题是while True: 创建了一个无限循环。您的except 子句有一个pass 语句,这意味着一旦发生错误,循环就会继续运行。相反,它可以写成

wait = WebDriverWait(driver, 10)
while True:
    try:
        element = wait.until(EC.element_to_be_clickable((By.LINK_TEXT, 'next')))
        html = driver.page_source
        soup = bs.BeautifulSoup(html,'html.parser')
        table = soup.find(id = 'search_main_div')
        classtitle =  table.find_all('p', class_= 'title')
        for aaa in classtitle:
            hrefsyo =  aaa.find('a', href = True)
            linkstoclick = hrefsyo.get('href')
            houselinklist.append(linkstoclick)
        element.click()
    except:
        break # change this to exit loop

一旦发生错误,循环将break 继续执行下一行代码

或者你也可以去掉while循环,用for循环遍历你的href链接列表

wait = WebDriverWait(driver, 10)
hrefLinks = ['link1','link2','link3'.....]
for link in hrefLinks:
    try:
        driver.get(link)
        element = wait.until(EC.element_to_be_clickable((By.LINK_TEXT, 'next')))
        html = driver.page_source
        soup = bs.BeautifulSoup(html,'html.parser')
        table = soup.find(id = 'search_main_div')
        classtitle =  table.find_all('p', class_= 'title')
        for aaa in classtitle:
            hrefsyo =  aaa.find('a', href = True)
            linkstoclick = hrefsyo.get('href')
            houselinklist.append(linkstoclick)
        element.click()
    except:
        pass #pass on error and move on to next hreflink

【讨论】:

    猜你喜欢
    • 2020-09-13
    • 1970-01-01
    • 2022-11-07
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 2021-01-31
    • 1970-01-01
    相关资源
    最近更新 更多