【问题标题】:Getting the href of the a tag获取 a 标签的 href
【发布时间】:2021-12-26 23:25:18
【问题描述】:

我想从cinch.co.uk 网站上抓取数据。我将 PythonBeautifulSoup4 和 Request 库一起使用。

对于每个汽车广告,我想进入每个链接,然后抓取汽车数据。 这是HTML and CSS of each ad。我可以看到,当我不点击 h3 标签时,文本是 ... ,但是,如果我点击它是 different

我遇到的问题是,当我进入 h3 标签级别(a 标签所在的位置)时,它似乎看不到它,因为我运行 ad = car.find('div', {'class': 'jB_k1'}).find('h3') 然后我打印(广告)我得到this。广告链接的唯一参考是该标签,因此我无法从其他标签获取链接。我有这个问题是因为网站使用 ::before 吗?

这是我迄今为止尝试过的:

"""
Method to get the HTML of a page
website - URL of the page

return - HTML of the page

"""
def getData(website):
       response = session.get(website)
       soup = BeautifulSoup(response.text, 'html.parser')
       return soup

"""
Method to get to  the next page
soup - html of a page

return - url of the next page or none if it doesn't exist
"""
def getNextPage(soup):
    pages = soup.find('ul', {'class' :'cf_gY'})
    pages = soup.find_all('li', {'class' : 'cf_kD'})
       
    website = None
    for page in pages:
        if page.find('a', {'aria-label' : 'Next page'}):
            website = 'http://www.cinch.co.uk' + str(page.find('a')['href'])
    
    return website
        
"""
Method to click onto a car ad
car - HTML of the car ad

return - URL of the car ad or none if it doesn't exist
"""
def getIntoPage(car):
    ad = 'https://www.cinch.co.uk' + car.find('a', {'class' : 'jB_dD'})['href']
    return ad

while True:

soup = getData(website)
website = getNextPage(soup)
nr+=1

#finds all the cars
cars = soup.find('ol', {'class': 'fJ_gY'})
cars = soup.find_all('article', {'class': 'lC_gQ lC_RB'})

for car in cars:
    
    ad = car.find('div', {'class': 'jB_k1'}).find('h3')
    getIntoPage(ad)
    break
break

我的中断语句仅用于测试一个广告,因为网站上有大量广告。

【问题讨论】:

    标签: python html css web-scraping beautifulsoup


    【解决方案1】:

    您遇到此问题是因为该网站使用了请求模块无法呈现的 javascript。到目前为止,我发现的唯一解决方案是将 selenium 与 webdriver 一起使用,并使用 javascript 呈现页面。不幸的是,据我所知,请求模块无法处理动态内容。

    【讨论】:

    • 我知道。我只是不想接受。 :)
    猜你喜欢
    • 2010-10-27
    • 2017-06-04
    • 2013-03-04
    • 2015-12-04
    • 2016-02-01
    • 2018-05-14
    • 2019-10-17
    • 1970-01-01
    相关资源
    最近更新 更多