Search code examples
pythonbeautifulsouphtml-parsing

Scraping an url using BeautifulSoup


Hello I am beginner in data scraping. At this case I want to get an url like "https:// . . ." but the result is a list in link variable that contain of all links in web. Here the code below;

import requests
from bs4 import BeautifulSoup
url = 'https://www.detik.com/search/searchall?query=KPK'
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
artikel = soup.findAll('div', {'class' : 'list media_rows list-berita'})
p = 1
link = []
for p in artikel:
     s = p.findAll('a', href=True)['href']
     link.append(s)

the result of the code above is getting error such as

TypeError                                 Traceback (most recent call last)
<ipython-input-141-469cb6eabf70> in <module>
3 link = []
4 for p in artikel:
5         s = p.findAll('a', href=True)['href']
6         link.append(s)
TypeError: list indices must be integers or slices, not str

The result is I want to get all links of https:// . . . in <div class = 'list media_rows list-berita' as a list Thank you in advance.


Solution

  • Code:

    import requests
    from bs4 import BeautifulSoup
    
    url = 'https://www.detik.com/search/searchall?query=KPK'
    page = requests.get(url)
    soup = BeautifulSoup(page.content, 'html.parser')
    articles = soup.findAll('div', {'class' : 'list media_rows list-berita'})
    links = []
    
    for article in articles:
        
        hrefs = article.find_all('a', href=True)
        for href in hrefs:
            links.append(href['href'])
            
    print(links)
    

    Output:

    ['https://news.detik.com/kolom/d-5609578/bahaya-laten-narasi-kpk-sudah-mati', 'https://news.detik.com/berita/d-5609585/penyuap-nurdin-abdullah-tawarkan-proyek-sulsel-ke-pengusaha-minta-rp-1-m', 'https://news.detik.com/berita/d-5609537/7-gebrakan-ahok-yang-bikin-geger', 'https://news.detik.com/berita/d-5609423/ppp-minta-bkn-jangan-asal-sebut-twk-kpk-dokumen-rahasia', 
    'https://news.detik.com/berita/d-5609382/mantan-sekjen-nasdem-gugat-pasal-suap-ke-mk-karena-dinilai-multitafsir', 'https://news.detik.com/berita/d-5609381/kpk-gali-informasi-soal-nurdin-abdullah-beli-tanah-pakai-uang-suap', 'https://news.detik.com/berita/d-5609378/hrs-bandingkan-kasus-dengan-pinangki-ary-askhara-tuntutan-ke-saya-gila', 'https://news.detik.com/detiktv/d-5609348/pimpinan-kpk-akhirnya-penuhi-panggilan-komnas-ham', 'https://news.detik.com/berita/d-5609286/wakil-ketua-kpk-nurul-ghufron-penuhi-panggilan-komnas-ham-soal-polemik-twk']