使用硒,美丽汤和蟒蛇进行网络抓取



目前正在抓取一个使用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

在此之后,我有另一个简单的抓取器,可以浏览列表列表,在硒中打开它们并收集该列表的数据。

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

问题是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

最新更新