Is there a way to extract the data from a UIWebView?

Is there a way to extract the first paragraph of each page from a UIWebView? I'm currently struggling with this task.

I've tried using a regular expression for detection, but unfortunately it's returning the paragraph class name instead of the actual content:

NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(<p\\s[\\
    S]*?=\\s*?['\"](.*?)['\"][\\s\\S]*?>)+?"
                             options:NSRegularExpressionCaseInsensitive
                             error:&error];

[regex enumerateMatchesInString:html
                        options:0
                        range:NSMakeRange(0, [html length])
                        usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL 
    *stop) {

    NSString *img = [html substringWithRange:[result rangeAtIndex:2]];
    NSLog(@"img src %@",img);
}];

NSString *classs=[webView stringByEvaluatingJavaScriptFromString:"document.getElementbyClassName(img)"];

Answer №1

To efficiently achieve this, you can use JavaScript code within the web view to locate and extract the text content of the first paragraph element in the document. This can be done using the

stringByEvaluatingJavaScriptFromString
method of UIWebView.

The following code snippet demonstrates how you can retrieve an array of all elements in the document with the tag name 'P'. It then verifies if there is at least one paragraph element present, returning its text content if so. Otherwise, it returns an empty string.

- (void)webViewDidFinishLoad:(UIWebView *)_webView
{
    NSString *code = @"var paragraphs = document.getElementsByTagName('P');"
                      "paragraphs.length > 0 ? paragraphs[0].innerText : '';";
    NSString *text = [_webView stringByEvaluatingJavaScriptFromString: code];
    // ... implement further actions with the extracted text ...
}

If necessary, you have the flexibility to run additional JavaScript code within the web view to inspect or alter other parts of the document.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on displaying the AJAX response in CakePHP 3.1

I'm working with a table that contains checkboxes. After selecting them, I want to calculate the sum of values from the table in a modal before confirming the form submission. Can someone guide me on how to render the AJAX response from the controller ...

Techniques for transferring information to Highchart directly from session storage

I am attempting to populate a pie highchart with data from a session storage variable, but I am not seeing any results. Here is the desired code: $(function () { Highcharts.chart('container', { chart: { type: 'pie', ...

The text field is unable to receive input by clicking a button, only registering values when physically typed into the field

I have three text fields with buttons to increment or decrement the value, and a final text field that displays the calculation of the values in each field. Everything is functioning correctly, however, the issue arises when I try to add values using the ...

Retaining selected items in Jquery UI Multiselect widget even after postback

I want to implement a GridView in asp.net that allows filtering on each column of the gridview, similar to Excel. To achieve this, I created a GridView and utilized the Jquery multiselect widget on the header of each column for filtering. <cc1:GridView ...

Node.js scheduler library for triggering events based on time in a cron-like fashion

Currently, I am utilizing Node.js to develop a web application. My aim is to trigger events at specific times. While I am aware of using setTimeout and computing the time difference from the present moment, this method does not account for various timezone ...

Is there a way to change a weather api into local time using ReactJS/JavaScript?

In order to display time in a specific format like 12:00 or 20:00 and change the background with images, I need to convert it to local time. This is essential for achieving my desired output. The JSON data structure that I am working with looks as follow ...

JavaScript's Blob to Base64 conversion using FileReader is failing to produce any output

In my typescript application, I am utilizing the FileReader to convert a blob into a base64 image for display within the template. adaptResultToBase64(res: Blob): string { let imageToDisplay : string | ArrayBuffer | null = ''; const re ...

Verify whether the user is obstructing third-party domain

I've encountered a recurring issue where many of our support calls pertain to images not loading due to users blocking Amazon S3 or a similar third-party service. I rely on third-party services for hosting images, videos, and certain JavaScript elemen ...

Spelling with iOS10's Speech Recognition Feature

I successfully integrated SpeechRecognizer by capturing audio from the microphone. The transcription is functioning properly, but I am interested in providing the user with the option to choose between Words or Spelling. For instance, if a user wishes to ...

Is there a way for me to verify if I have already made an AJAX data request

I have an image gallery with thumbnails. When a user clicks on a thumbnail, an ajax request is fired. I want to prevent the ajax request from firing again if the user clicks on the same thumbnail and instead use the existing data. $.getJSON(url, function( ...

Error: The function is not defined on this.props during the handleCHange event

After going through numerous answers to similar questions on this topic, I believe that I am following all the necessary steps but for some reason, it is not working. Below is the specific section of code that is causing the error: import React from &apos ...

Employing CSS animations to elevate div elements

Currently, I am working on animating a table of divs and trying to achieve an effect where a new div enters and "bumps up" the existing ones. In my current setup, Message i3 is overlapping Message 2 instead of bumping it up. How can I make Messages 1 and 2 ...

Persist the checkbox value in the database and update the status of the label accordingly

I need a checkbox for user preference selection that is stored in a MySQL database for constant availability. The label should change to "Enabled" when the checkbox is selected and vice versa. Upon saving (submitting) the page, an alert message should disp ...

What steps do I need to follow to send a POST request using JavaScript in Django while including the CSRF token?

I've encountered a similar issue where the solutions provided didn't quite work for me: Fetch, set-cookies and csrf Proper Django CSRF validation using fetch post request Even though I believe my post request content is correct, I still keep g ...

If the user is not authenticated, Node.js will redirect them to the login page

I've integrated the node-login module for user login on my website. Once a user logs in, the dashboard.html page is rendered: app.get('/', function(req, res){ // Check if the user's credentials are stored in a cookie // if (req.coo ...

Scrolling triggers the click event

Within my JavaScript code, I have a rather simple event listener set up to listen for a click: element.addeventlistener('click', ()=>{ #do somthing }) However, I am encountering an issue on IOS (iPhone) where scrolling triggers the event list ...

Why does `npm init react-app` automatically select yarn as the default package manager? (npm version 6.14.5)

After executing the command npm init react-app, I noticed that npm automatically selects yarn as the default package manager for the newly created app. To resolve this, I followed the steps provided in How Do I Uninstall Yarn to remove yarn from my system. ...

Unusual trait of TrackballControls.target within the world of Three.js

My current project involves simulating a 3D distribution of galaxies. In this simulation, the galaxies are represented as points. question1.htm references galaxydata1.txt to calculate and load the galaxy positions: rawFile.open("GET", "galaxydata1.txt", ...

Getting access to the source codes of my application

Encountered a dilemma and seeking assistance on how to resolve it. Collaborated with a developer to develop an IOS and Android app. Initially, it was a paid app but now I want to offer it for free with ads after 6 months. However, the developer informs m ...

iOS, a data logger that utilizes SQL technology

I'm facing some errors and unfortunately, I can't figure out what I'm doing wrong. What I need is a statement that will insert tripname, timestamp, lat, longi, accuracy, and speed into the database. Even though I have set up the database, I ...