使用BeautifulSoup进行网页抓取时,如何移动到新页面?

2024-06-30 16:32:20 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是从craigslist上提取记录的代码。一切都很好,但我需要能够进入下一组记录,重复相同的过程,但作为一个新的编程我被卡住了。从页面代码来看,我应该单击此处span中包含的箭头按钮,直到它不包含href:

<a href="/search/syp?s=120" class="button next" title="next page">next &gt; </a> 

我在想也许这是一个循环中的循环,但我想这也可能是一个try/except情况。听起来对吗?你将如何实现这一点?在

^{pr2}$

Tags: 代码search过程编程记录button页面箭头
2条回答

这不是如何访问“下一步”按钮的直接答案,但这可能是您的问题的解决方案。当我在过去浏览网页时,我会使用每个页面的url来循环搜索结果。 在craiglist上,当你点击“下一页”时,网址就会改变。这种变化通常有一种模式可以利用。我不需要花很长时间看,但看起来craigslist的第二页是:https://nh.craigslist.org/search/syp?s=120,第三页是https://nh.craigslist.org/search/syp?s=240。看起来URL的最后一部分每次都会更改120次。 您可以创建一个120的倍数列表,然后构建一个for循环,将该值添加到每个URL的末尾。 然后在这个for循环中嵌套当前的for循环。在

对于每个抓取的页面,您可以找到下一个要爬网的url并将其添加到列表中。在

我就是这样做的,不需要对你的代码做太多修改。我添加了一些评论,以便您了解发生了什么,但如果您需要任何其他解释,请给我留言:

import requests
from urllib.request import urlopen
import pandas as pd
from bs4 import BeautifulSoup


base_url = 'https://nh.craigslist.org/d/computer-parts/search/syp'
base_search_url = 'https://nh.craigslist.org'
urls = []
urls.append(base_url)
dates = []
titles = []
prices = []
hoods = []

while len(urls) > 0: # while we have urls to crawl
    print(urls)
    url = urls.pop(0) # removes the first element from the list of urls
    response = requests.get(url)
    soup = BeautifulSoup(response.text,"lxml")
    next_url = soup.find('a', class_= "button next") # finds the next urls to crawl
    if next_url: # if it's not an empty string
        urls.append(base_search_url + next_url['href']) # adds next url to crawl to the list of urls to crawl

    listings = soup.find_all('li', class_= "result-row") # get all current url listings
    # this is your code unchanged
    for listing in listings:
        datar = listing.find('time', {'class': ["result-date"]}).text
        dates.append(datar)

        title = listing.find('a', {'class': ["result-title"]}).text
        titles.append(title)

        try:
            price = listing.find('span', {'class': "result-price"}).text
            prices.append(price)
        except:
            prices.append('missing')

        try:
            hood = listing.find('span', {'class': "result-hood"}).text
            hoods.append(hood)
        except:
            hoods.append('missing')

#write the lists to a dataframe
listings_df = pd.DataFrame({'Date': dates, 'Titles' : titles, 'Price' : prices, 'Location' : hoods})

 #write to a file
listings_df.to_csv("craigslist_listings.csv")

编辑:您还忘记在代码中导入BeautifulSoup,我在我的回复中添加了这一点 Edit2:您只需要找到“下一步”按钮的第一个实例,因为页面可以(在本例中确实)有多个“下一步”按钮。
Edit3:若要对此计算机部件进行爬网,base_url应更改为此代码中的一个

相关问题 更多 >