Python网络抓取转到下一页

时间:2018-10-09 13:00:23

标签: python web-scraping webpage

该代码只是一次又一次地打印相同的电子邮件地址,而不会转到下一页。有人在我的代码中看到错误了吗?

import requests
from bs4 import BeautifulSoup as soup
def get_emails(_links:list):
for i in range(len(_links)):
 new_d = soup(requests.get(_links[i]).text, 'html.parser').find_all('a', {'class':'my_modal_open'})
 if new_d:
   yield new_d[-1]['title']

start=20
while True:
d = soup(requests.get('http://www.schulliste.eu/type/gymnasien/?bundesland=&start=20').text, 'html.parser')

results = [i['href'] for i in d.find_all('a')][52:-9]
results = [link for link in results if link.startswith('http://')]
print(list(get_emails(results)))

next_page=d.find('div', {'class': 'paging'}, 'weiter')

if next_page:

    d=next_page.get('href')
    start+=20
else:
    break

当您按下按钮“ weiter”(下一页)时,urlending从“ ... start = 20”更改为“ start = 40”。由于每个站点有20个结果,因此需要20秒的步骤。

2 个答案:

答案 0 :(得分:0)

问题与您请求的网址有关。每次都请求相同的url,因为您没有按照计算的起始时间更新url。尝试像这样更改网址:

'http://www.schulliste.eu/type/gymnasien/?bundesland=&start={}'.format(start)

答案 1 :(得分:0)

假设next_page返回任何内容,问题是您试图一次执行两次相同的操作,但操作均不正确:

1。)您试图将d指向下一页,但是在循环的开始,您再次将d重新分配给了起始页面。

2。)您正在尝试为下一页分配start+=20,但是在代码的任何部分都没有引用start

因此,您有两种解决方法:

1。)将d分配移到循环外,并完全删除start对象:

# start=20
# You don't need start because it's not being used at all

# move the initial d assignment outside the loop
d = soup(requests.get('http://www.schulliste.eu/type/gymnasien/?bundesland=&start=20').text, 'html.parser')
while True:
    # rest of your code

if next_page:

    d=next_page.get('href')
    # start+=20
    # Again, you don't need the start any more.
else:
    break

2。)无需重新分配d,只需在循环开始时在您的url中引用start,并在d中删除if next_page分配:< / p>

start=20
while True:
d = soup(requests.get('http://www.schulliste.eu/type/gymnasien/?bundesland=&start={page_id}'.format(page_id=start).text, 'html.parser')

# rest of your code

if next_page:

    # d=next_page.get('href')
    # this d assignment is redundant as it will get reassigned in the loop.  Start is your key.
    start+=20
else:
    break
相关问题