【发布时间】:2019-04-03 18:06:18
【问题描述】:
我正在尝试使用以下链接抓取两个网页:
https://www.boligportal.dk/lejebolig/dp/2-vaerelses-lejlighed-holstebro/id-5792074' https://www.boligportal.dk/lejebolig/dp/2-vaerelses-lejlighed-odense-m/id-5769482
我想提取链接中每个房子的信息。我使用 selenium 而不是 beautifulsoup,因为页面是动态的,并且 beautifulsoup 不会检索所有 HTML 代码。我使用下面的代码来尝试实现这一点。
page_links=['https://www.boligportal.dk/lejebolig/dp/2-vaerelses-lejlighed-holstebro/id-5792074',
'https://www.boligportal.dk/lejebolig/dp/2-vaerelses-lejlighed-odense-m/id-5769482']
def render_page(url):
driver = webdriver.Firefox()
driver.get(url)
time.sleep(3)
r = driver.page_source
driver.quit()
return(r)
def remove_html_tags(text):
clean = re.compile('<.*?>')
return(re.sub(clean, '', text))
houses_html_code = []
housing_data = []
address = []
# Loop through main pages, render them and extract code
for i in page_links:
html = render_page(str(i))
soup = BeautifulSoup(html, "html.parser")
houses_html_code.append(soup)
for i in houses_html_code:
for span_1 in soup.findAll('span', {"class": "AdFeatures__item-value"}):
housing_data.append(remove_html_tags(str(span_1)))
所以我总结了我渲染页面,获取页面源,将页面源附加到列表并在两个渲染页面的页面源中搜索跨度类。
但是,我的代码两次返回第一个链接的页面源,实际上忽略了第二个页面链接,即使它呈现每个页面(firefox 会随每个页面弹出)。请参阅下面的输出。
为什么这不起作用?对不起,如果答案很明显。我对 Python 比较陌生,这是我第一次使用 selenium
['Lejlighed',
'82 m²',
'2',
'5. sal',
'Nej',
'Ja',
'Nej',
'-',
'Ubegrænset',
'Snarest',
'8.542,-',
'-',
'25.626,-',
'-',
'34.168,-',
'24/08-2018',
'3775136',
'Lejlighed',
'82 m²',
'2',
'5. sal',
'Nej',
'Ja',
'Nej',
'-',
'Ubegrænset',
'Snarest',
'8.542,-',
'-',
'25.626,-',
'-',
'34.168,-',
'24/08-2018',
'3775136']
【问题讨论】:
标签: python loops selenium web-scraping