Reputation: 331
import requests
from bs4 import BeautifulSoup
import pandas as pd
header = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.11',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding': 'none',
'Accept-Language': 'en-US,en;q=0.8',
'Connection': 'keep-alive'}
def scrap_hrefs(url,baseUrl):
resp = requests.get(url, headers= header)
respData = BeautifulSoup(resp.content, 'html.parser')
allHrefs = respData.select('[href]')
return allHrefs, baseUrl
def get_hrefs(allHrefs, baseUrl):
for i in range(0,len(allHrefs)):
if allHrefs[i]['href'].startswith('/'):
allHrefs[i]= baseUrl + allHrefs[i]['href']
else:
allHrefs[i]= allHrefs[i]['href']
return allHrefs
def store_hrefs(allHrefs):
links = {'links' : allHrefs}
df = pd.DataFrame(links).drop_duplicates()
for i in range(len(df.index)):
if df['links'].str.contains('https')==False:
df.drop()
df.to_csv("example_home_page_links.csv", index=False)
return df
def run_scraper(url,baseUrl) :
store_hrefs(get_hrefs(*scrap_hrefs(url, baseUrl)))
run_scraper('https://www.example.com/','https://www.example.com')
this code is giving the following error :
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
I want to remove all the rows in which 'https' is not there(i.e. remove all the invalid links/content).
Upvotes: 1
Views: 851
Reputation: 862761
You can change remove False
output in loop:
for i in range(len(df.index)):
if df['links'].str.contains('https')==False:
df.drop()
to filter only rows with match condition in boolean indexing
:
df = df[df['links'].str.contains('https')]
Upvotes: 2