gpt4 book ai didi

python - 使用selenium循环链接并获取页面源

转载 作者:太空宇宙 更新时间:2023-11-03 21:38:40 26 4
gpt4 key购买 nike

我正在尝试使用以下链接抓取两个网页:

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']

最佳答案

您有一个拼写错误更改:

for span_1 in soup.findAll('span', {"class": "AdFeatures__item-value"}):

for span_1 in i.findAll('span', {"class": "AdFeatures__item-value"}):

但是为什么要为每个页面创建一个新的网络驱动程序呢?为什么不做这样的事情:

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']
driver = webdriver.Firefox()

def render_page(url):
driver.get(url)
...

...
for i in houses_html_code:
for span_1 in i.findAll('span', {"class": "AdFeatures__item-value"}):
housing_data.append(remove_html_tags(str(span_1)))

driver.quit()

输出:

['Lejlighed', '78 m²', '2', '2. sal', 'Nej', 'Nej', 'Nej', '-', 'Ubegrænset', 'Snarest', '5.300,-', '800,-', '15.900,-', '0,-', '22.000,-', '27/10-2018', '3864958', 'Lejlighed', '82 m²', '2', '5. sal', 'Nej', 'Ja', 'Nej', '-', 'Ubegrænset', 'Snarest', '8.542,-', '-', '25.626,-', '-', '34.168,-', '24/08-2018', '3775136']

关于python - 使用selenium循环链接并获取页面源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53068700/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com