繁体   English   中英

获取a标签的href

[英]Getting the href of the a tag

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

对于每个汽车广告,我想进入每个链接,然后抓取汽车数据。 这是每个广告HTML 和 CSS 我可以看到,当我没有点击 h3 标签时,文本是“...”,但是如果我点击它是不同的

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM