so, i have 10 webpages,each are academicsite presenting abstract in front of them. you know, html pattern where the abstracts are usually kept in meta tag, div tag, trd tag, you decide the best. i need a func that accept link, identify where is the abstract paragraph, extract it, then return it.
Assistant
To create a function that extracts the abstract from academic webpages, we'll use Python along with libraries such as requests and BeautifulSoup. The function will accept a URL, fetch the webpage content, and then attempt to locate the abstract within common HTML tags. Here’s a sample function:
python
import requests
from bs4 import BeautifulSoup
def extract_abstract(url):
try:
# Send a GET request to the URL
response = requests.get(url)
response.raise_for_status() # Raise an error for bad responses
# Parse the HTML content
soup = BeautifulSoup(response.content, 'html.parser')
# Attempt to find the abstract in common tags
# You can adjust the tags and classes based on the specific HTML structure
abstract = None
# Check common tags for the abstract
possible_tags = ['meta[name="description"]', 'div', 'p']
for tag in possible_tags:
if tag == 'meta[name="description"]':
meta_abstract = soup.select_one(tag)
if meta_abstract:
abstract = meta_abstract.get('content')
break
# Look for paragraphs or divs with 'abstract' class or similar
for element in soup.find_all(tag):
if 'abstract' in element.get('class', []):
abstract = element.get_text(strip=True)
break
if abstract:
break
if not abstract:
print("Abstract not found.")
return abstract.strip() if abstract else None
except requests.RequestException as e:
print(f"Error fetching the URL: {e}")
return None
# Example usage:
url = "https://example-academic-site.com/paper"
abstract_text = extract_abstract(url)
print(abstract_text)
User
put detailed logs to the func. use termcolor to color important pars; green, red, pink, orange color.
Assistant
To enhance the function with detailed logging and color coding for important parts using the termcolor library, you can modify the function as follows:
First, ensure you have the termcolor library installed:
bash
pip install termcolor
Below is the modified code:
python
import requests
from bs4 import BeautifulSoup
from termcolor import colored
def extract_abstract(url):
try:
# Send a GET request to the URL
print(colored(f"Fetching URL: {url}...", 'orange'))
response = requests.get(url)
response.raise_for_status() # Raise an error for bad responses
print(colored("Successfully fetched the URL.", 'green'))
# Parse the HTML content
soup = BeautifulSoup(response.content, 'html.parser')
print(colored("HTML content successfully parsed.", 'green'))
# Attempt to find the abstract in common tags
abstract = None
possible_tags = ['meta[name="description"]', 'div', 'p']
print(colored("Searching for the abstract in possible tags...", 'orange'))
# Check meta tags
meta_abstract = soup.select_one('meta[name="description"]')
if meta_abstract:
abstract = meta_abstract.get('content')
print(colored("Found abstract in meta tag.", 'pink'))
return abstract.strip()
# Check other common tags
for tag in possible_tags:
for element in soup.find_all(tag):
if 'abstract' in element.get('class', []):
abstract = element.get_text(strip=True)
print(colored("Found abstract in a <div> or <p> tag.", 'pink'))
return abstract.strip()
if not abstract:
print(colored("Abstract not found in any common tags.", 'red'))
return None
except requests.RequestException as e:
print(colored(f"Error fetching the URL: {str(e)}", 'red'))
return None
# Example usage:
url = "https://example-academic-site.com/paper"
abstract_text = extract_abstract(url)
if abstract_text:
print(colored(f"Extracted Abstract: {abstract_text}", 'green'))
else:
print(colored("No abstract was extracted.", 'red'))
User
this was the log output. i immediately receive '403 forbidden' after i scrape the first abstract. is this mean i am blocked? this is log output:
Receiving a "403 Forbidden" error indicates that the server is denying access to the requested resource. This commonly happens for a few reasons, especially when scraping websites:
User-Agent Blocking: Many websites block requests that do not come from standard web browsers. By default, the requests library uses its own user-agent in the headers that identify it as a script. Some websites look for and reject these requests.
IP Blocking: If you are making too many requests in a short time frame, your IP address may be temporarily or permanently blocked by the website for suspected scraping behavior.
Other Security Measures: Websites may employ various anti-scraping measures, including requiring JavaScript to render content or using CAPTCHA validations that cannot be solved programmatically.
Solutions:
Set a User-Agent:
You can configure your request to mimic a real browser's user agent by setting the User-Agent header. Here’s how you can modify your code to include headers:
Implement Delays:
Consider adding delays between requests to avoid being blocked for sending too many requests too quickly. The time.sleep() function can help here.
python
import time
# After each request
time.sleep(2) # Sleeps for 2 seconds
Use Proxies:
If your IP gets blocked frequently, consider using a proxy service to rotate IP addresses for your requests.
Check Robots.txt:
Always check the website’s robots.txt file (e.g., https://example.com/robots.txt) to see the rules they have regarding web scraping.
Headless Browsers:
For websites that require JavaScript for content rendering, consider using a headless browser solution like Selenium, which simulates a real browser, allowing you to bypass some restrictions.
Here’s how you might combine a User-Agent with your function:
User
below is CustomGoogleScholarOrganic script from organic_search.py script of google_scholar_py lib. i rarely get block when using this method, tho i use it side by side with proxy rotater and ratelimiter monitorer. i notice a line driver.get(f'https://scholar.google.com/scholar?q={query}&hl=en&gl=us&start={page_num}'). this is the one that do scraping, right? this one seems effective. we can use this. can you modify this code so that we can use it to scrape abstract from custom link instead? below is the code:
from selenium import webdriver
from selenium_stealth import stealth
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selectolax.lexbor import LexborHTMLParser
from typing import List, Dict, Callable
import time, random, re
import pandas as pd
from pathlib import Path
class CustomGoogleScholarOrganic:
def init(self) -> None:
pass
code
Assistant
To modify the CustomGoogleScholarOrganic class so it can scrape abstracts from custom links instead of Google Scholar, we need to primarily change the scrape_google_scholar_organic_results method to accept a URL, load the page, and extract the abstract. We'll focus on web scraping using Selenium and adjust the parsing logic accordingly.
Here’s the modified version of the CustomGoogleScholarOrganic class, now renamed as CustomAbstractScraper, which can scrape abstracts from provided URLs:
python
User
can u write the full code with detailed logging and coloring?
Assistant
Here’s the full code for the CustomAbstractScraper class with detailed logging and colored output using the termcolor library. This version implements the ability to scrape abstracts from a provided list of URLs, and it includes improved logging to provide feedback on the scraping process.
First, ensure you have the required libraries by installing them if you haven't done so:
the current abstract identification logic dont work. use abstract identification logic from your extract_abstract func, but adjust it to context of our parse_abstract and scrape_abstracts func. also, change 'orange' code to 'yellow' and 'pink' to 'light_magenta'.
Assistant
I've updated the CustomAbstractScraper class to incorporate the abstract identification logic you mentioned from the previous extract_abstract function. The class now attempts to find the abstract within various possible HTML structures, reflecting the pattern we discussed earlier.
Here's the complete code with the requested modifications, including the changes to color codes:
Sure! Here's the complete code for the CustomAbstractScraper class with the specified URLs added to the urls variable. This version will attempt to scrape abstracts from these links.
python
User
below is ascript. this script hold a method named scrape_scholar that scrape every link returned by gscholar search result. u will find it use proxy_handler, rate_limit_manager and proxy_rotation_manager in it. the scrape return a list of dict items holding information about each link, with title_link (string link that lead to the link) being one of key in the dict. i want you to use logic in our code to add one new method that take single title_link as input, then scrape the link's content to extract abstract. use our code logic in it. then add one method that loop this method to all title_links kept by scrape_scholar's result. use use proxy_handler, rate_limit_manager and proxy_rotation_manager if you need. you decide. script:
scraper.py
import requests
from google_scholar_py import CustomGoogleScholarOrganic
import json
from proxy_handler import setup_proxy
from rate_limit_manager import call_with_rate_limit
from proxy_rotation_manager import proxy_generator
import string
from bs4 import BeautifulSoup
class ScholarScraper:
def init(self, search_query, max_results=5):
self.search_query = search_query
self.max_results = max_results
# create several attributes here
code
def scrape_scholar(self) -> list:
# Initialize the scraper
parser = CustomGoogleScholarOrganic()
# Get the next proxy address
proxy_address = next(proxy_generator)
# Setup the proxy connection
driver = setup_proxy(proxy_address)
# Use rate limiting to call the scraping function
self.scholar_scrape_result = call_with_rate_limit(parser.scrape_google_scholar_organic_results,
query=self.search_query,
pagination=False,
save_to_csv=False,
save_to_json=False)
return self.scholar_scrape_result
Example usage
if name == "main":
scraper = ScholarScraper(search_query="sadness psychology", max_results=5)
# example here
Assistant
To meet your requirements, I'll add a method to the ScholarScraper class that takes a title_link from the search results and scrapes the abstract using the logic we developed earlier. We will also implement another method that loops through each title_link returned by the scrape_scholar method to extract their abstracts.
Here’s the updated scraper.py code with the added methods:
python
User
also, please add detailed loggings with colors to the script.
Assistant
Sure! Below is the updated ScholarScraper class with detailed logging included, using colored output to provide clear feedback at each step of the scraping process. I've included log messages for major actions and results, as well as error handling.
python
User
also, i find scrape logic in scrape_abstract no longer idneitfy abstract. can you check whats wrong?
Assistant
Let's review the abstract extraction logic in the scrape_abstract method. The main purpose of this method is to identify and extract the abstract from the provided title_link. Here’s the key extraction logic currently implemented in the scrape_abstract method:
python
# Attempting to find the abstract using the previous logic
possible_tags = ['meta[name="description"]', 'div', 'p']
for tag in possible_tags:
if tag == 'meta[name="description"]':
meta_abstract = parser.css_first(tag)
if meta_abstract:
abstract = meta_abstract.attrs['content']
print(colored("Abstract found in meta tag.", 'light_magenta'))
break
for element in parser.css(tag):
if 'abstract' in element.attrs.get('class', []):
abstract = element.text()
print(colored("Abstract found in a <div> or <p> tag with 'abstract' class.", 'light_magenta'))
break
if abstract:
break
Issues and Improvements:
Meta Tag Issue:
The presence of an abstract in the meta description tag is not guaranteed for most academic papers or articles. While some websites may use this tag for a summary, many do not. This check alone may not be sufficient.
Div and P Tag Logic:
The current logic looks for the class 'abstract' in div or p elements. Depending on the site, the class used for the abstract content may vary.
Proposed Adjustments:
Let's enhance the scrape_abstract method by increasing its robustness, allowing it to check various potential structures more thoroughly.
Here's the revised scrape_abstract method:
python
User
lets refer back to CustomAbstractScraper. scraper in scrape_abstracts method of CustomAbstractScraper work. successfully return abstract text. but when you apply it to ScholarScraper, it no longer work. refer to scrape_abstracts method of CustomAbstractScraper to see what changes are made. i personally suspect the html content change due to parse difference.
Assistant
Thank you for your patience and for pointing this out! Let's investigate the differences that might be causing the issue.
Key Observations:
HTML Parsing Libraries: The original CustomAbstractScraper uses selectolax for parsing, and you might be using a different approach within the ScholarScraper. Ensure that both scraper classes are using the same parser for consistency.
Element Selection: The method to select elements and extract the abstract might differ between the two classes. The CustomAbstractScraper directly utilizes LexborHTMLParser, while in the ScholarScraper, we may not have ensured that the parsing logic mirrors what was successful before.
Let’s refine the scrape_abstract method within the ScholarScraper class to ensure that we are accurately extracting the abstract in the same way as is done in the CustomAbstractScraper. We will also provide more robust checks and output to help identify issues.
Here’s the revised scrape_abstract method within the ScholarScraper class:
python
User
i rewrite the code. this one work. see whats different on this one. also, can you do proxy_handler rate_limit_manager proxy_rotation_manager on the scrape_abstract method? here is script code:
scholar_scraper.py
from typing import List, Dict
from selenium import webdriver
from selenium_stealth import stealth
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selectolax.lexbor import LexborHTMLParser
import requests
from google_scholar_py import CustomGoogleScholarOrganic
import json
from proxy_handler import setup_proxy
from rate_limit_manager import call_with_rate_limit
from proxy_rotation_manager import proxy_generator
import string
from selectolax.lexbor import LexborHTMLParser
import time
import random
from termcolor import colored
Thank you for sharing the updated ScholarScraper code. Let's analyze the differences compared to the previous version and how we can integrate the proxy_handler, rate_limit_manager, and proxy_rotation_manager into the scrape_abstract method.
Key Differences and Improvements
Dedicated Parsing Method: The code now includes a separate parse_abstract method which is specifically designed to extract the abstract. This method takes a LexborHTMLParser object as an argument. This is a cleaner separation of concerns, making both scraping and parsing more modular.
HTML Parsing Consistency: The parsing logic checks both the meta tag and common tags like div and p for the abstract text, similar to what was previously working for you. This ensures that you are effectively targeting multiple potential sources for the abstract.
Efficient Driver Usage: The scrape_abstract method initializes the WebDriver and performs all necessary tasks within the same method, encapsulating the functionality better.
Using the Same Parser for Consistency: The parser that is utilized is consistent throughout the code, thus reducing the risk of discrepancies during scraping activities.
Logging: The log messages provide clear information about the scraping process and what the scraper finds, making it easier to debug or understand the flow of operations.
Suggested Changes to Integrate Proxy and Rate Limiting in scrape_abstract
To incorporate the proxy_handler, rate_limit_manager, and proxy_rotation_manager into the scrape_abstract method, we can modify the method to set up a proxy for each individual abstract scraping call and apply rate limiting as well. Here’s how you can do that:
python
User
it return error: Error while scraping abstract with rate limit: ScholarScraper.scrape_abstract.<locals>.<lambda>() got an unexpected keyword argument 'rate_limit_time'
Assistant
The error you're encountering indicates that the lambda function you are using with call_with_rate_limit is not set up to accept the keyword argument rate_limit_time. This typically means that the lambda function itself needs to reference the original scraping method without passing additional parameters that it's not expecting.
In your case, you're wrapping a method call within a lambda. Since you're trying to set a rate limit, but the call_with_rate_limit function doesn't support passing additional arguments through a lambda in this way, we can adjust the implementation as follows:
Updated scrape_abstract Method
We’ll modify the function to ensure that call_with_rate_limit calls the _scrape_with_proxy method correctly without supplying unintended keyword arguments. Here's how we can do that:
python
def scrape_abstract(self, url: str) -> str:
'''
Extracts abstracts from the provided URL.
Arguments:
- url: URL to scrape abstracts from.
'''
# Get the next proxy address
proxy_address = next(proxy_generator)
print(colored(f"Using proxy address for abstract scraping: {proxy_address}", 'cyan'))
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
# Chrome options for stealth
options.add_experimental_option('excludeSwitches', ['enable-automation', 'enable-logging'])
options.add_experimental_option('useAutomationExtension', False)
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=options)
stealth(driver,
languages=['en-US', 'en'],
vendor='Google Inc.',
platform='Win32',
webgl_vendor='Intel Inc.',
renderer='Intel Iris OpenGL Engine',
fix_hairline=True,
)
print(colored(f"Fetching URL: {url}...", 'yellow'))
# Use rate limiting
scraped_abstract = None
try:
scraped_abstract = call_with_rate_limit(self._scrape_with_proxy, driver, url, rate_limit_time=1)
except Exception as e:
print(colored(f"Error while scraping abstract with rate limit: {e}", 'red'))
driver.quit()
print(colored("Driver closed. Scraping completed.", 'green'))
return scraped_abstract
def _scrape_with_proxy(self, driver: webdriver.Chrome, url: str) -> str:
driver.get(url)
time.sleep(random.randint(1, 3)) # Sleep to avoid getting blocked
parser = LexborHTMLParser(driver.page_source)
scraped_abstract = self.parse_abstract(parser_containing_link=parser)
return scraped_abstract
Not yet included in a published release.
Key Points:
Libraries Used:
requests for fetching webpage content.
BeautifulSoup (from bs4) for parsing HTML.
Abstract Extraction:
The function looks for abstracts in meta tags (commonly used for descriptions), div tags, and p tags.
You can customize the selection further based on the specific structure of the academic sites you are dealing with.
Error Handling:
The function handles HTTP request errors and returns None if it fails to find the abstract or encounters issues.
Make sure to install the required libraries using:
bash
pip install requests beautifulsoup4
You can adjust the logic based on the specific patterns you observe in your academic sites.
Detailed Logging:
Fetch URL: Indicates that the function is attempting to fetch the webpage.
Success Messages: It logs successful fetches and parsing.
Search Process: It informs when it is searching for the abstract and which tags it is checking.
Found Abstract: If the abstract is found, which tag it was found in is logged.
Failure to Find: Informs if no abstract was found, logged in red.
Color Coding:
Green: Successful actions.
Red: Errors or failures.
Pink: Important discoveries (e.g., when an abstract is found).
Orange: Ongoing actions or processes.
You can run this enhanced function, and it will provide you with detailed, colored logs indicating each step of the process.
python
import requests
from bs4 import BeautifulSoup
from termcolor import colored
import time
def extract_abstract(url):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36'
}
try:
print(colored(f"Fetching URL: {url}...", 'orange'))
response = requests.get(url, headers=headers)
response.raise_for_status()
print(colored("Successfully fetched the URL.", 'green'))
# ... [rest of your code remains unchanged] ...
except requests.RequestException as e:
print(colored(f"Error fetching the URL: {str(e)}", 'red'))
return None
# Example usage with a delay between requests
urls = ["https://example.com/your-url1", "https://example.com/your-url2"] # List of URLs to scrape
for url in urls:
abstract_text = extract_abstract(url)
if abstract_text:
print(colored(f"Extracted Abstract: {abstract_text}", 'green'))
else:
print(colored("No abstract was extracted.", 'red'))
time.sleep(2) # Delay between requests
By following these steps and implementing these strategies, you can often mitigate the likelihood of receiving 403 errors while scraping.
def parse(self, parser: Callable, organic_results_data: Callable):
'''
Arugments:
- parser: Lexbor parser from scrape_google_scholar_organic_results() function.
- organic_results_data: List to append data to. List origin location is scrape_google_scholar_organic_results() function. Line 104.
This function parses data from Google Scholar Organic results and appends data to a List.
It's used by scrape_google_scholar_organic_results().
It returns nothing as it appends data to `organic_results_data`,
which appends it to `organic_results_data` List in the scrape_google_scholar_organic_results() function.
'''
for result in parser.css('.gs_r.gs_or.gs_scl'):
try:
title: str = result.css_first('.gs_rt').text()
except: title = None
try:
title_link: str = result.css_first('.gs_rt a').attrs['href']
except: title_link = None
try:
publication_info: str = result.css_first('.gs_a').text()
except: publication_info = None
try:
snippet: str = result.css_first('.gs_rs').text()
except: snippet = None
try:
# if Cited by is present in inline links, it will be extracted
cited_by_link = ''.join([link.attrs['href'] for link in result.css('.gs_ri .gs_fl a') if 'Cited by' in link.text()])
except: cited_by_link = None
try:
# if Cited by is present in inline links, it will be extracted and type cast it to integer
cited_by_count = int(''.join([re.search(r'\d+', link.text()).group() for link in result.css('.gs_ri .gs_fl a') if 'Cited by' in link.text()]))
except: cited_by_count = None
try:
pdf_file: str = result.css_first('.gs_or_ggsm a').attrs['href']
except: pdf_file = None
organic_results_data.append({
'title': title,
'title_link': title_link,
'publication_info': publication_info,
'snippet': snippet if snippet else None,
'cited_by_link': f'https://scholar.google.com{cited_by_link}' if cited_by_link else None,
'cited_by_count': cited_by_count if cited_by_count else None,
'pdf_file': pdf_file
})
#TODO: add lang support. https://serpapi.com/google-languages
def scrape_google_scholar_organic_results(
self,
query: str,
pagination: bool = False,
save_to_csv: bool = False,
save_to_json: bool = False
) -> List[Dict[str, str]]:
'''
Extracts data from Google Scholar Organic resutls page:
- title: str
- title_link: str
- publication_info: str
- snippet: str
- cited_by_link: str
- cited_by_count: int
- pdf_file: str
Arguments:
- query: str. Search query.
- pagination: bool. Enables or disables pagination. Default is False.
- save_to_csv: bool. True of False. Default is False.
- save_to_json: bool. True of False. Default is False.
Usage:
from google_scholar_py import CustomGoogleScholarOrganic
parser = CustomGoogleScholarOrganic()
data = parser.scrape_google_scholar_organic_results(
query='blizzard',
pagination=False,
save_to_csv=True
)
for organic_result in data:
print(organic_result['title'])
print(organic_result['pdf_file'])
'''
# selenium stealth
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_experimental_option('excludeSwitches', ['enable-automation', 'enable-logging'])
options.add_experimental_option('useAutomationExtension', False)
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=options)
stealth(driver,
languages=['en-US', 'en'],
vendor='Google Inc.',
platform='Win32',
webgl_vendor='Intel Inc.',
renderer='Intel Iris OpenGL Engine',
fix_hairline=True,
)
page_num = 0
organic_results_data = []
# parse all pages
if pagination:
while True:
# parse all pages
driver.get(f'https://scholar.google.com/scholar?q={query}&hl=en&gl=us&start={page_num}')
parser = LexborHTMLParser(driver.page_source)
self.parse(parser=parser, organic_results_data=organic_results_data)
# pagination
if parser.css_first('.gs_ico_nav_next'): # checks for the "Next" page button
page_num += 10 # paginate to the next page
time.sleep(random.randint(1, 3)) # sleep between paginations
else:
break
else:
# parse first page only
driver.get(f'https://scholar.google.com/scholar?q={query}&hl=en&gl=us&start={page_num}')
parser = LexborHTMLParser(driver.page_source)
self.parse(parser=parser, organic_results_data=organic_results_data)
if save_to_csv:
pd.DataFrame(data=organic_results_data).to_csv('google_scholar_organic_results_data.csv',
index=False, encoding='utf-8')
if save_to_json:
pd.DataFrame(data=organic_results_data).to_json('google_scholar_organic_results_data.json',
orient='records')
driver.quit()
return organic_results_data
from selenium import webdriver
from selenium_stealth import stealth
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selectolax.lexbor import LexborHTMLParser
from typing import List, Dict, Callable
import time, random
import pandas as pd
class CustomAbstractScraper:
def __init__(self):
pass
def parse_abstract(self, parser: Callable, results_data: List):
'''
This function parses the abstract from a given page and appends it to a results list.
'''
try:
# Assuming the abstract is contained within a <div> or <p> tag with a specific class or id, update accordingly
abstract_element = parser.css_first('div.abstract-class') # Update the selector based on actual HTML structure
if abstract_element:
abstract = abstract_element.text()
results_data.append({'abstract': abstract})
else:
results_data.append({'abstract': None})
except Exception as e:
print(f"Error parsing abstract: {e}")
results_data.append({'abstract': None})
def scrape_abstracts(self, urls: List[str], save_to_csv: bool = False, save_to_json: bool = False) -> List[Dict[str, str]]:
'''
Extracts abstracts from the provided list of URLs.
Arguments:
- urls: List of URLs to scrape abstracts from.
- save_to_csv: bool. True or False. Default is False.
- save_to_json: bool. True or False. Default is False.
Returns:
- List of dictionaries with extracted abstracts.
'''
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
# Chrome options for stealth
options.add_experimental_option('excludeSwitches', ['enable-automation', 'enable-logging'])
options.add_experimental_option('useAutomationExtension', False)
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=options)
stealth(driver,
languages=['en-US', 'en'],
vendor='Google Inc.',
platform='Win32',
webgl_vendor='Intel Inc.',
renderer='Intel Iris OpenGL Engine',
fix_hairline=True,
)
results_data = []
for url in urls:
print(f"Fetching URL: {url}")
driver.get(url)
time.sleep(random.randint(1, 3)) # Sleep to avoid getting blocked
parser = LexborHTMLParser(driver.page_source)
self.parse_abstract(parser=parser, results_data=results_data)
if save_to_csv:
pd.DataFrame(data=results_data).to_csv('abstracts_data.csv', index=False, encoding='utf-8')
if save_to_json:
pd.DataFrame(data=results_data).to_json('abstracts_data.json', orient='records')
driver.quit()
return results_data
Key Changes Made:
Renamed Class: Changed the class name to CustomAbstractScraper.
New Method: Replaced scrape_google_scholar_organic_results with scrape_abstracts, which accepts a list of URLs.
Parsing Function: Added a new method parse_abstract to handle the extraction of the abstract from the webpage. Update the CSS selector in parser.css_first('div.abstract-class') based on the actual structure of the pages you are scraping.
Data Structure: The collected data now consists solely of abstracts, stored in a dictionary format.
CSV/JSON Saving: The option to save extracted abstracts as CSV or JSON files remains functional.
Usage Example:
You can now use this new class to scrape abstracts like so:
python
scraper = CustomAbstractScraper()
urls = [
"https://example.com/your-first-abstract-url",
"https://example.com/your-second-abstract-url",
# Add more URLs as needed
]
data = scraper.scrape_abstracts(urls, save_to_csv=True)
for item in data:
print(item['abstract'])
Make sure to adjust the CSS selectors based on the actual HTML structure of the pages you're targeting to accurately extract the abstract content.
from selenium import webdriver
from selenium_stealth import stealth
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selectolax.lexbor import LexborHTMLParser
from typing import List, Dict
import time
import random
import pandas as pd
from termcolor import colored
class CustomAbstractScraper:
def __init__(self):
pass
def parse_abstract(self, parser: LexborHTMLParser, results_data: List[Dict[str, str]]):
'''
This function parses the abstract from a given page and appends it to the results list.
'''
try:
# Assuming the abstract is contained within a <div> or <p> tag, update the selector based on actual HTML structure
abstract_element = parser.css_first('div.abstract-class') # Change this CSS selector to match the target site's structure
if abstract_element:
abstract = abstract_element.text()
results_data.append({'abstract': abstract})
print(colored("Abstract found and added to results.", 'green'))
else:
results_data.append({'abstract': None})
print(colored("No abstract found on this page.", 'yellow'))
except Exception as e:
print(colored(f"Error parsing abstract: {e}", 'red'))
results_data.append({'abstract': None})
def scrape_abstracts(self, urls: List[str], save_to_csv: bool = False, save_to_json: bool = False) -> List[Dict[str, str]]:
'''
Extracts abstracts from the provided list of URLs.
Arguments:
- urls: List of URLs to scrape abstracts from.
- save_to_csv: bool. True or False. Default is False.
- save_to_json: bool. True or False. Default is False.
Returns:
- List of dictionaries with extracted abstracts.
'''
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
# Chrome options for stealth
options.add_experimental_option('excludeSwitches', ['enable-automation', 'enable-logging'])
options.add_experimental_option('useAutomationExtension', False)
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=options)
stealth(driver,
languages=['en-US', 'en'],
vendor='Google Inc.',
platform='Win32',
webgl_vendor='Intel Inc.',
renderer='Intel Iris OpenGL Engine',
fix_hairline=True,
)
results_data = []
for url in urls:
print(colored(f"Fetching URL: {url}...", 'orange'))
driver.get(url)
time.sleep(random.randint(1, 3)) # Sleep to avoid getting blocked
parser = LexborHTMLParser(driver.page_source)
self.parse_abstract(parser=parser, results_data=results_data)
if save_to_csv:
pd.DataFrame(data=results_data).to_csv('abstracts_data.csv', index=False, encoding='utf-8')
print(colored("Extracted abstracts saved to 'abstracts_data.csv'.", 'green'))
if save_to_json:
pd.DataFrame(data=results_data).to_json('abstracts_data.json', orient='records', lines=True)
print(colored("Extracted abstracts saved to 'abstracts_data.json'.", 'green'))
driver.quit()
print(colored("Driver closed. Scraping completed.", 'green'))
return results_data
# Example usage
if __name__ == "__main__":
scraper = CustomAbstractScraper()
urls = [
"https://example.com/your-first-abstract-url", # Replace with actual URLs
"https://example.com/your-second-abstract-url",
# Add more URLs as needed
]
data = scraper.scrape_abstracts(urls, save_to_csv=True, save_to_json=True)
for item in data:
print(colored(f"Extracted Abstract: {item['abstract']}", 'green'))
Detailed Logging and Color Coding:
Color Coding:
Green: Indicates successful actions such as finding an abstract or saving output files.
Red: Displays error messages related to the parsing process.
Yellow: Indicates when no abstract is found on a page.
Orange: Used for fetching URLs, marking the process being started.
Logging Messages:
Each significant step in the scraping process prints out a message providing feedback on the operation's status.
Usage:
The URLs in the urls list should be updated to the actual pages you intend to scrape.
By default, the script saves the abstracts in both CSV and JSON formats.
Adjustments Needed:
Make sure to change the CSS selector in abstract_element = parser.css_first('div.abstract-class') to correspond to the actual HTML structure of the pages you are working with. This selector is a placeholder and needs to reflect the class or ID used for abstracts on the target websites.
from selenium import webdriver
from selenium_stealth import stealth
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selectolax.lexbor import LexborHTMLParser
from typing import List, Dict
import time
import random
import pandas as pd
from termcolor import colored
class CustomAbstractScraper:
def __init__(self):
pass
def parse_abstract(self, parser: LexborHTMLParser, results_data: List[Dict[str, str]]):
'''
This function parses the abstract from a given page and appends it to the results list.
'''
possible_tags = ['meta[name="description"]', 'div', 'p'] # Possible tags where abstracts may be found
abstract = None
try:
# Check for abstract in common tags
for tag in possible_tags:
if tag == 'meta[name="description"]':
meta_abstract = parser.css_first(tag)
if meta_abstract:
abstract = meta_abstract.attrs['content']
print(colored("Abstract found in meta tag.", 'light_magenta'))
break
for element in parser.css(tag):
if 'abstract' in element.attrs.get('class', []):
abstract = element.text()
print(colored("Abstract found in a <div> or <p> tag with 'abstract' class.", 'light_magenta'))
break
if abstract:
break
if not abstract:
results_data.append({'abstract': None})
print(colored("No abstract found on this page.", 'yellow'))
else:
results_data.append({'abstract': abstract})
except Exception as e:
print(colored(f"Error parsing abstract: {e}", 'red'))
results_data.append({'abstract': None})
def scrape_abstracts(self, urls: List[str], save_to_csv: bool = False, save_to_json: bool = False) -> List[Dict[str, str]]:
'''
Extracts abstracts from the provided list of URLs.
Arguments:
- urls: List of URLs to scrape abstracts from.
- save_to_csv: bool. True or False. Default is False.
- save_to_json: bool. True or False. Default is False.
Returns:
- List of dictionaries with extracted abstracts.
'''
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
# Chrome options for stealth
options.add_experimental_option('excludeSwitches', ['enable-automation', 'enable-logging'])
options.add_experimental_option('useAutomationExtension', False)
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=options)
stealth(driver,
languages=['en-US', 'en'],
vendor='Google Inc.',
platform='Win32',
webgl_vendor='Intel Inc.',
renderer='Intel Iris OpenGL Engine',
fix_hairline=True,
)
results_data = []
for url in urls:
print(colored(f"Fetching URL: {url}...", 'yellow'))
driver.get(url)
time.sleep(random.randint(1, 3)) # Sleep to avoid getting blocked
parser = LexborHTMLParser(driver.page_source)
self.parse_abstract(parser=parser, results_data=results_data)
if save_to_csv:
pd.DataFrame(data=results_data).to_csv('abstracts_data.csv', index=False, encoding='utf-8')
print(colored("Extracted abstracts saved to 'abstracts_data.csv'.", 'green'))
if save_to_json:
pd.DataFrame(data=results_data).to_json('abstracts_data.json', orient='records', lines=True)
print(colored("Extracted abstracts saved to 'abstracts_data.json'.", 'green'))
driver.quit()
print(colored("Driver closed. Scraping completed.", 'green'))
return results_data
# Example usage
if __name__ == "__main__":
scraper = CustomAbstractScraper()
urls = [
"https://example.com/your-first-abstract-url", # Replace with actual URLs
"https://example.com/your-second-abstract-url",
# Add more URLs as needed
]
data = scraper.scrape_abstracts(urls, save_to_csv=True, save_to_json=True)
for item in data:
print(colored(f"Extracted Abstract: {item['abstract']}", 'green'))
Summary of Changes:
Abstract Identification Logic:
The parse_abstract now tries to find the abstract in various tags: meta[name="description"], div, and p. You may update the selectors as per the actual structure of the sites you intend to scrape.
Color Changes:
Changed the color for the fetching URL message from 'orange' to 'yellow'.
Changed the color for found abstracts from 'pink' to 'light_magenta'.
Logging:
Logging messages provide clear feedback on whether an abstract was found, and where it was found, or if no abstract was detected.
Adjust the CSS selectors based on the website you are targeting to ensure effective scraping. The code is now set up to provide detailed feedback on its operations while trying to extract abstract information.
from selenium import webdriver
from selenium_stealth import stealth
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selectolax.lexbor import LexborHTMLParser
from typing import List, Dict
import time
import random
import pandas as pd
from termcolor import colored
class CustomAbstractScraper:
def __init__(self):
pass
def parse_abstract(self, parser: LexborHTMLParser, results_data: List[Dict[str, str]]):
'''
This function parses the abstract from a given page and appends it to the results list.
'''
possible_tags = ['meta[name="description"]', 'div', 'p'] # Possible tags where abstracts may be found
abstract = None
try:
# Check for abstract in common tags
for tag in possible_tags:
if tag == 'meta[name="description"]':
meta_abstract = parser.css_first(tag)
if meta_abstract:
abstract = meta_abstract.attrs['content']
print(colored("Abstract found in meta tag.", 'light_magenta'))
break
for element in parser.css(tag):
if 'abstract' in element.attrs.get('class', []):
abstract = element.text()
print(colored("Abstract found in a <div> or <p> tag with 'abstract' class.", 'light_magenta'))
break
if abstract:
break
if not abstract:
results_data.append({'abstract': None})
print(colored("No abstract found on this page.", 'yellow'))
else:
results_data.append({'abstract': abstract})
except Exception as e:
print(colored(f"Error parsing abstract: {e}", 'red'))
results_data.append({'abstract': None})
def scrape_abstracts(self, urls: List[str], save_to_csv: bool = False, save_to_json: bool = False) -> List[Dict[str, str]]:
'''
Extracts abstracts from the provided list of URLs.
Arguments:
- urls: List of URLs to scrape abstracts from.
- save_to_csv: bool. True or False. Default is False.
- save_to_json: bool. True or False. Default is False.
Returns:
- List of dictionaries with extracted abstracts.
'''
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
# Chrome options for stealth
options.add_experimental_option('excludeSwitches', ['enable-automation', 'enable-logging'])
options.add_experimental_option('useAutomationExtension', False)
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=options)
stealth(driver,
languages=['en-US', 'en'],
vendor='Google Inc.',
platform='Win32',
webgl_vendor='Intel Inc.',
renderer='Intel Iris OpenGL Engine',
fix_hairline=True,
)
results_data = []
for url in urls:
print(colored(f"Fetching URL: {url}...", 'yellow'))
driver.get(url)
time.sleep(random.randint(1, 3)) # Sleep to avoid getting blocked
parser = LexborHTMLParser(driver.page_source)
self.parse_abstract(parser=parser, results_data=results_data)
if save_to_csv:
pd.DataFrame(data=results_data).to_csv('abstracts_data.csv', index=False, encoding='utf-8')
print(colored("Extracted abstracts saved to 'abstracts_data.csv'.", 'green'))
if save_to_json:
pd.DataFrame(data=results_data).to_json('abstracts_data.json', orient='records', lines=True)
print(colored("Extracted abstracts saved to 'abstracts_data.json'.", 'green'))
driver.quit()
print(colored("Driver closed. Scraping completed.", 'green'))
return results_data
# Example usage
if __name__ == "__main__":
scraper = CustomAbstractScraper()
urls = [
"https://www.frontiersin.org/journals/psychology/articles/10.3389/fpsyg.2017.00288/full",
"https://psycnet.apa.org/record/1993-98937-032",
"https://www.tandfonline.com/doi/abs/10.1111/ap.12232",
"https://www.sciencedirect.com/science/article/pii/S1057740812000757",
"https://compass.onlinelibrary.wiley.com/doi/abs/10.1111/spc3.12229",
]
data = scraper.scrape_abstracts(urls, save_to_csv=True, save_to_json=True)
for item in data:
print(colored(f"Extracted Abstract: {item['abstract']}", 'green'))
Summary:
The provided URLs are included in the urls variable.
The scraping process looks for abstracts in potential HTML structure tags specified in the parse_abstract method.
The output logging provides feedback on the scraping status, which can help you understand where the process is successful or where issues arise.
Remember to adjust any HTML selectors in the parse_abstract function as necessary to align with the actual structure of the pages you're scraping to ensure effective extraction of the abstracts.
# scraper.py
import requests
from google_scholar_py import CustomGoogleScholarOrganic
import json
from proxy_handler import setup_proxy
from rate_limit_manager import call_with_rate_limit
from proxy_rotation_manager import proxy_generator
import string
from selectolax.lexbor import LexborHTMLParser
from bs4 import BeautifulSoup
import time
import random
from termcolor import colored
class ScholarScraper:
def __init__(self, search_query, max_results=5):
self.search_query = search_query
self.max_results = max_results
self.scholar_scrape_result = []
def scrape_scholar(self) -> list:
# Initialize the scraper
parser = CustomGoogleScholarOrganic()
# Get the next proxy address
proxy_address = next(proxy_generator)
# Setup the proxy connection
driver = setup_proxy(proxy_address)
# Use rate limiting to call the scraping function
self.scholar_scrape_result = call_with_rate_limit(parser.scrape_google_scholar_organic_results,
query=self.search_query,
pagination=False,
save_to_csv=False,
save_to_json=False)
return self.scholar_scrape_result
def scrape_abstract(self, title_link: str) -> str:
'''
Scrapes the abstract from the given title_link.
'''
print(colored(f"Scraping abstract from: {title_link}", 'yellow'))
# Create a new instance of the driver for scraping the abstract
proxy_address = next(proxy_generator)
driver = setup_proxy(proxy_address)
try:
# Navigate to the title_link
driver.get(title_link)
time.sleep(random.randint(1, 3)) # Sleep to avoid being blocked
# Parse the page source
parser = LexborHTMLParser(driver.page_source)
abstract = None
# Attempting to find the abstract using the logic from previous code
possible_tags = ['meta[name="description"]', 'div', 'p']
for tag in possible_tags:
if tag == 'meta[name="description"]':
meta_abstract = parser.css_first(tag)
if meta_abstract:
abstract = meta_abstract.attrs['content']
print(colored("Abstract found in meta tag.", 'light_magenta'))
break
for element in parser.css(tag):
if 'abstract' in element.attrs.get('class', []):
abstract = element.text()
print(colored("Abstract found in a <div> or <p> tag with 'abstract' class.", 'light_magenta'))
break
if abstract:
break
if not abstract:
print(colored("No abstract found on this page.", 'yellow'))
return None
return abstract
except Exception as e:
print(colored(f"Error while scraping abstract: {e}", 'red'))
return None
finally:
driver.quit()
def scrape_all_abstracts(self) -> list:
'''
Loops through the scholar_scrape_result and scrapes abstracts from all title_links.
'''
abstracts = []
print(colored("Starting to scrape abstracts from all title links...", 'yellow'))
for result in self.scholar_scrape_result:
title_link = result.get('title_link')
if title_link:
abstract = self.scrape_abstract(title_link)
abstracts.append({
'title_link': title_link,
'abstract': abstract
})
return abstracts
# Example usage
if __name__ == "__main__":
scraper = ScholarScraper(search_query="sadness psychology", max_results=5)
results = scraper.scrape_scholar()
abstracts = scraper.scrape_all_abstracts()
for item in abstracts:
print(colored(f"Title Link: {item['title_link']}", 'green'))
print(colored(f"Abstract: {item['abstract']}", 'green'))
Explanation of Added Methods:
scrape_abstract Method:
Takes a title_link as input.
Uses the proxy setup to scrape the link's page and extract the abstract using the previous logic.
Returns the abstract as a string or None if not found.
scrape_all_abstracts Method:
Loops through the list of title links obtained from scrape_scholar.
Calls the scrape_abstract method for each link and aggregates the results into a list of dictionaries containing the title_link and the extracted abstract.
Improvised Proxy, Rate Limiting, and Error Handling:
The scraping of abstracts is wrapped with proper error handling, ensuring the program continues even if one of the links fails.
Each call to scrape an abstract can utilize the proxy and rate-limiting strategies already present.
This code structure should help you effectively scrape abstracts from the results returned by the Google Scholar search, while also using the desired functionality related to proxies and rate limiting.
# scraper.py
import requests
from google_scholar_py import CustomGoogleScholarOrganic
import json
from proxy_handler import setup_proxy
from rate_limit_manager import call_with_rate_limit
from proxy_rotation_manager import proxy_generator
import string
from selectolax.lexbor import LexborHTMLParser
import time
import random
from termcolor import colored
class ScholarScraper:
def __init__(self, search_query, max_results=5):
self.search_query = search_query
self.max_results = max_results
self.scholar_scrape_result = []
def scrape_scholar(self) -> list:
'''Scrapes Google Scholar results based on the search query.'''
print(colored(f"Starting to scrape Google Scholar for query: {self.search_query}", 'yellow'))
# Initialize the scraper
parser = CustomGoogleScholarOrganic()
# Get the next proxy address
proxy_address = next(proxy_generator)
print(colored(f"Using proxy address: {proxy_address}", 'cyan'))
# Setup the proxy connection
driver = setup_proxy(proxy_address)
# Use rate limiting to call the scraping function
try:
self.scholar_scrape_result = call_with_rate_limit(parser.scrape_google_scholar_organic_results,
query=self.search_query,
pagination=False,
save_to_csv=False,
save_to_json=False)
print(colored("Successfully scraped Google Scholar results.", 'green'))
except Exception as e:
print(colored(f"Error while scraping Google Scholar results: {e}", 'red'))
return self.scholar_scrape_result
def scrape_abstract(self, title_link: str) -> str:
'''Scrapes the abstract from a given title_link.'''
print(colored(f"Scraping abstract from: {title_link}", 'yellow'))
# Create a new instance of the driver for scraping the abstract
proxy_address = next(proxy_generator)
print(colored(f"Using proxy address for abstract scraping: {proxy_address}", 'cyan'))
driver = setup_proxy(proxy_address)
try:
# Navigate to the title_link
driver.get(title_link)
time.sleep(random.randint(1, 3)) # Sleep to avoid being blocked
print(colored(f"Successfully navigated to {title_link}", 'green'))
# Parse the page source
parser = LexborHTMLParser(driver.page_source)
abstract = None
# Attempting to find the abstract using the previous logic
possible_tags = ['meta[name="description"]', 'div', 'p']
for tag in possible_tags:
if tag == 'meta[name="description"]':
meta_abstract = parser.css_first(tag)
if meta_abstract:
abstract = meta_abstract.attrs['content']
print(colored("Abstract found in meta tag.", 'light_magenta'))
break
for element in parser.css(tag):
if 'abstract' in element.attrs.get('class', []):
abstract = element.text()
print(colored("Abstract found in a <div> or <p> tag with 'abstract' class.", 'light_magenta'))
break
if abstract:
break
if not abstract:
print(colored("No abstract found on this page.", 'yellow'))
return None
print(colored("Abstract successfully extracted.", 'green'))
return abstract
except Exception as e:
print(colored(f"Error while scraping abstract: {e}", 'red'))
return None
finally:
driver.quit()
print(colored("Driver closed after scraping abstract.", 'green'))
def scrape_all_abstracts(self) -> list:
'''Scrapes abstracts from all title links present in the scholar_scrape_result.'''
abstracts = []
print(colored("Starting to scrape abstracts from all title links...", 'yellow'))
for result in self.scholar_scrape_result:
title_link = result.get('title_link')
if title_link:
abstract = self.scrape_abstract(title_link)
abstracts.append({
'title_link': title_link,
'abstract': abstract
})
print(colored("Finished scraping abstracts from all title links.", 'green'))
return abstracts
# Example usage
if __name__ == "__main__":
scraper = ScholarScraper(search_query="sadness psychology", max_results=5)
results = scraper.scrape_scholar()
if results:
abstracts = scraper.scrape_all_abstracts()
for item in abstracts:
print(colored(f"Title Link: {item['title_link']}", 'green'))
print(colored(f"Abstract: {item['abstract']}", 'green' if item['abstract'] else 'red'))
else:
print(colored("No results found in Google Scholar.", 'red'))
Detailed Logging:
Starting Actions: Logs when the scraping starts for the Google Scholar results and when abstracts are being scraped.
Proxy Address: Prints the proxy address being used for each scraping task, improving transparency.
Success Messages: Logs successful navigation to pages and extraction of abstracts, providing positive feedback.
Error Messages: Catches exceptions and logs them in red, indicating issues during scraping.
Completion Logs: Communicates the closing of the driver and the completion of tasks.
Color Coding: Uses specific colors for different types of messages:
Yellow: For starting actions.
Cyan: For displaying the proxy addresses.
Green: For successful operations.
Light Magenta: For finding abstracts.
Red: For error messages and failures.
This setup will give you clear feedback on progress and help you identify potential issues with the scraping process, all while maintaining the use of proxies and rate limiting as needed in your scraping flow. Adjust the CSS selectors and the logic in the scrape_abstract method if you encounter different website structures.
def scrape_abstract(self, title_link: str) -> str:
'''Scrapes the abstract from a given title_link.'''
print(colored(f"Scraping abstract from: {title_link}", 'yellow'))
# Create a new instance of the driver for scraping the abstract
proxy_address = next(proxy_generator)
print(colored(f"Using proxy address for abstract scraping: {proxy_address}", 'cyan'))
driver = setup_proxy(proxy_address)
try:
# Navigate to the title_link
driver.get(title_link)
time.sleep(random.randint(1, 3)) # Sleep to avoid being blocked
print(colored(f"Successfully navigated to {title_link}", 'green'))
# Parse the page source
parser = LexborHTMLParser(driver.page_source)
abstract = None
# Check for abstract in common tags
possible_tags = [
'meta[name="description"]',
'div', # Could contain the abstract
'p', # Could also contain the abstract
'section', # Some articles might have sections for the abstract
]
# Loop through possible tags and search for the abstract
for tag in possible_tags:
if tag == 'meta[name="description"]':
meta_abstract = parser.css_first(tag)
if meta_abstract:
abstract = meta_abstract.attrs['content']
print(colored("Abstract found in meta tag.", 'light_magenta'))
break # Found an abstract in meta tag, exit loop
for element in parser.css(tag):
# Adjust this check for common class names found in abstract sections
if 'abstract' in element.attrs.get('class', []) or 'summary' in element.attrs.get('class', []):
abstract = element.text().strip() # Clean up whitespace
print(colored("Abstract found in a <div> or <p> or <section> tag.", 'light_magenta'))
break
if abstract:
break # If we found the abstract, exit the outer loop
if not abstract:
print(colored("No abstract found on this page.", 'yellow'))
return None
print(colored("Abstract successfully extracted.", 'green'))
return abstract
except Exception as e:
print(colored(f"Error while scraping abstract: {e}", 'red'))
return None
finally:
driver.quit()
print(colored("Driver closed after scraping abstract.", 'green'))
Key Improvements:
Expanded Possible Tags: Added section to the list of tags checked, which is another common container for abstract content on many academic articles.
Flexible Class Check: The logic now checks for both the abstract class and the summary class in tags. This can be adjusted further depending on the specific article layouts you encounter.
Whitespace Handling: The extracted text from any tag is stripped of leading and trailing whitespace to keep it clean.
Testing:
To ensure this solution works efficiently:
Run the scraper against various articles to see which tags return valid abstracts.
Monitor the output logs to verify locations where abstracts are successfully identified or print any additional errors.
By implementing these changes and guidelines, the abstract extraction logic should be more effective in identifying and scraping abstracts from a variety of academic papers.
def scrape_abstract(self, title_link: str) -> str:
'''Scrapes the abstract from a given title_link.'''
print(colored(f"Scraping abstract from: {title_link}", 'yellow'))
# Create a new instance of the driver for scraping the abstract
proxy_address = next(proxy_generator)
print(colored(f"Using proxy address for abstract scraping: {proxy_address}", 'cyan'))
driver = setup_proxy(proxy_address)
try:
# Navigate to the title_link
driver.get(title_link)
time.sleep(random.randint(1, 3)) # Sleep to avoid being blocked
print(colored(f"Successfully navigated to {title_link}", 'green'))
# Parse the page source
parser = LexborHTMLParser(driver.page_source)
abstract = None
# Check for abstract in common tags
possible_tags = [
'meta[name="description"]',
'div', # Could contain the abstract
'p', # Could also contain the abstract
'section', # Some articles might have sections for the abstract
]
# Loop through possible tags and search for the abstract
for tag in possible_tags:
if tag == 'meta[name="description"]':
meta_abstract = parser.css_first(tag)
if meta_abstract:
abstract = meta_abstract.attrs['content']
print(colored("Abstract found in meta tag.", 'light_magenta'))
break # Found an abstract in meta tag, exit loop
for element in parser.css(tag):
# Here you can add more checks based on what you've learned from the structure.
if 'abstract' in element.attrs.get('class', []) or 'summary' in element.attrs.get('class', []):
abstract = element.text().strip() # Clean up whitespace
print(colored("Abstract found in a class-based tag.", 'light_magenta'))
break
if abstract:
break # If we found the abstract, exit the outer loop
if not abstract:
print(colored("No abstract found on this page.", 'yellow'))
return None
print(colored("Abstract successfully extracted.", 'green'))
return abstract
except Exception as e:
print(colored(f"Error while scraping abstract: {e}", 'red'))
return None
finally:
driver.quit()
print(colored("Driver closed after scraping abstract.", 'green'))
Important Points:
Using the Same Parsing Logic: Ensure the use of LexborHTMLParser for parsing HTML content consistently.
More Comprehensive Tag Checking: Maintain the same logic as previously discussed, which includes checking both the meta tags and standard tags like div, p, and so forth.
Element Selection by Class: You might want to add additional checks for HTML class names that often hold abstract content, like summary or others that you know to be specific to the articles you’re scraping.
Testing:
After implementing these changes, test the scrape_abstract method within ScholarScraper to see if it successfully extracts the abstract from the provided links.
Consider logging the HTML structure when debugging to help understand any discrepancies you may encounter when applying the methods to different scraping contexts.
Debugging Steps:
Print out the HTML content of the page right after navigating to it and right before parsing. This can help you understand what the page structure looks like and what may be causing the extraction to fail.
Verify that the articles you're testing still use the same HTML structure as before. Academic publishers may change their HTML layout or may require additional scraping logic (like dealing with JavaScript-rendered content).
By ensuring that your methods are aligned and by carefully checking the HTML structures, you should be able to identify and resolve the issues affecting abstract extraction in your ScholarScraper.
def scrape_scholar(self) -> list:
'''Scrapes Google Scholar results based on the search query.'''
print(colored(f"Starting to scrape Google Scholar for query: {self.search_query}", 'yellow'))
# Initialize the scraper
parser = CustomGoogleScholarOrganic()
# Get the next proxy address
proxy_address = next(proxy_generator)
print(colored(f"Using proxy address: {proxy_address}", 'cyan'))
# Setup the proxy connection
driver = setup_proxy(proxy_address)
# Use rate limiting to call the scraping function
try:
self.scholar_scrape_result = call_with_rate_limit(parser.scrape_google_scholar_organic_results,
query=self.search_query,
pagination=False,
save_to_csv=False,
save_to_json=False)
print(colored("Successfully scraped Google Scholar results.", 'green'))
except Exception as e:
print(colored(f"Error while scraping Google Scholar results: {e}", 'red'))
return self.scholar_scrape_result
def parse_abstract(self, parser_containing_link: LexborHTMLParser):
'''
This function parses the abstract from a given page and appends it to the results list.
'''
possible_tags = ['meta[name="description"]', 'div', 'p'] # Possible tags where abstracts may be found
abstract = None
try:
# Check for abstract in common tags
for tag in possible_tags:
if tag == 'meta[name="description"]':
meta_abstract = parser_containing_link.css_first(tag)
if meta_abstract:
abstract = meta_abstract.attrs['content']
print(colored("Abstract found in meta tag.", 'light_magenta'))
break
for element in parser_containing_link.css(tag):
if 'abstract' in element.attrs.get('class', []):
abstract = element.text()
print(colored("Abstract found in a <div> or <p> tag with 'abstract' class.", 'light_magenta'))
break
if abstract:
break
return abstract
except Exception as e:
print(colored(f"Error parsing abstract: {e}", 'red'))
return None
def scrape_abstract(self, url: str) -> str:
'''
Extracts abstracts from the provided URL.
Arguments:
- url: URL to scrape abstracts from.
'''
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
# Chrome options for stealth
options.add_experimental_option('excludeSwitches', ['enable-automation', 'enable-logging'])
options.add_experimental_option('useAutomationExtension', False)
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=options)
stealth(driver,
languages=['en-US', 'en'],
vendor='Google Inc.',
platform='Win32',
webgl_vendor='Intel Inc.',
renderer='Intel Iris OpenGL Engine',
fix_hairline=True,
)
results_data = []
print(colored(f"Fetching URL: {url}...", 'yellow'))
driver.get(url)
time.sleep(random.randint(1, 3)) # Sleep to avoid getting blocked
parser = LexborHTMLParser(driver.page_source)
scraped_abstract = self.parse_abstract(parser_containing_link=parser)
driver.quit()
print(colored("Driver closed. Scraping completed.", 'green'))
return scraped_abstract
Example usage
if name == "main":
scraper = ScholarScraper(search_query="sadness psychology", max_results=5)
results = scraper.scrape_scholar()
if results:
code
abstracts = scraper.scrape_abstract('https://www.frontiersin.org/articles/10.3389/fpsyg.2017.00288/full')
for item in [abstracts]:
print(f"Result: {item}")
#print(colored(f"Title Link: {item['title_link']}", 'green'))
#print(colored(f"Abstract: {item['abstract']}", 'green' if item['abstract'] else 'red'))
else:
print(colored("No results found in Google Scholar.", 'red'))
def scrape_abstract(self, url: str) -> str:
'''
Extracts abstracts from the provided URL.
Arguments:
- url: URL to scrape abstracts from.
'''
# Get the next proxy address
proxy_address = next(proxy_generator)
print(colored(f"Using proxy address for abstract scraping: {proxy_address}", 'cyan'))
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
# Chrome options for stealth
options.add_experimental_option('excludeSwitches', ['enable-automation', 'enable-logging'])
options.add_experimental_option('useAutomationExtension', False)
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=options)
stealth(driver,
languages=['en-US', 'en'],
vendor='Google Inc.',
platform='Win32',
webgl_vendor='Intel Inc.',
renderer='Intel Iris OpenGL Engine',
fix_hairline=True,
)
print(colored(f"Fetching URL: {url}...", 'yellow'))
# Use rate limiting
scraped_abstract = None
try:
scraped_abstract = call_with_rate_limit(lambda: self._scrape_with_proxy(driver, url),
rate_limit_time=1) # Set your desired rate limit time
except Exception as e:
print(colored(f"Error while scraping abstract with rate limit: {e}", 'red'))
driver.quit()
print(colored("Driver closed. Scraping completed.", 'green'))
return scraped_abstract
def _scrape_with_proxy(self, driver: webdriver.Chrome, url: str) -> str:
driver.get(url)
time.sleep(random.randint(1, 3)) # Sleep to avoid getting blocked
parser = LexborHTMLParser(driver.page_source)
scraped_abstract = self.parse_abstract(parser_containing_link=parser)
return scraped_abstract
Key Changes in the Revised scrape_abstract Method:
Proxy Address: Before fetching the URL, the method retrieves a new proxy address from the proxy_rotation_manager.
Rate Limiting: I added a call to the call_with_rate_limit method. This manages the timing of requests to avoid hitting any rate limits on the target website.
Separate Proxy Scraping Logic: The actual scraping action has been moved to a helper method _scrape_with_proxy for clarity, handling the waiting and parsing in isolation from the main method.
Explanation of the Changes:
_scrape_with_proxy: This helper function takes the driver and the URL as inputs, allowing the main scrape_abstract function to remain focused on setting up the environment and handling success/error responses.
Rate Limiting: The logic ensures that every abstract scraping is managed adequately, avoiding too many requests within a short period.
Conclusion:
The updated structure helps with maintaining clarity, modularity, and efficiency in your scraping operations while handling proxies and rate limits effectively. This should help resolve any issues with abstract extraction and make the operation more solid. Make sure to test this thoroughly with the articles you intend to scrape!
Key Changes:
Directly Pass Function: The call_with_rate_limit method now directly references self._scrape_with_proxy. This way, we're not wrapping it in a lambda that alters the expected behavior.
Arguments Passed: The driver and url are passed as arguments directly, along with any needed rate limiting arguments, so you maintain the required functionality without running into argument mismatch issues.
Final Considerations:
Make sure that call_with_rate_limit is designed to accept these kind of function calls with the proper arguments.
Test the implementation to ensure that it correctly applies rate limiting, scraping, and proxy usage as intended throughout your operations.
With these adjustments, the function should work as expected, reducing the chance of hitting any rate limits while scraping abstracts.