I am using Flutter and want to parse HTML using parser.dart
<div class="weather-item now"><!-- now -->
<span class="time">Now</span>
<div class="temp">19.8<span>℃</span>
<small>(23℃)</small>
</div>
<table>
<tr>
<th><i class="icon01" aria-label="true"></i></th>
<td>93%</td>
</tr>
<tr>
<th><i class="icon02" aria-label="true"></i></th>
<td>south 2.2km/h</td>
</tr>
<tr>
<th><i class="icon03" aria-label="true"></i></th>
<td>-</td>
</tr>
</table>
</div>
Using,
import 'package:html/parser.dart';
I want to get this data
Now,19.8,23,93%,south 2.2km/h
How can I do this?
Since you are using the html package, you can get the desired data like so using some html parsing and string processing (as needed), here is a dart sample, you can use the parseData function as is in your flutter application -
main.dart
import 'package:html/parser.dart' show parse;
main(List<String> args) {
parseData();
}
parseData(){
var document = parse("""
<div class="weather-item now"><!-- now -->
<span class="time">Now</span>
<div class="temp">19.8<span>℃</span>
<small>(23℃)</small>
</div>
<table>
<tr>
<th><i class="icon01" aria-label="true"></i></th>
<td>93%</td>
</tr>
<tr>
<th><i class="icon02" aria-label="true"></i></th>
<td>south 2.2km/h</td>
</tr>
<tr>
<th><i class="icon03" aria-label="true"></i></th>
<td>-</td>
</tr>
</table>
</div>
""");
//declaring a list of String to hold all the data.
List<String> data = [];
data.add(document.getElementsByClassName("time")[0].innerHtml);
//declaring variable for temp since we will be using it multiple places
var temp = document.getElementsByClassName("temp")[0];
data.add(temp.innerHtml.substring(0, temp.innerHtml.indexOf("<span>")));
data.add(temp.getElementsByTagName("small")[0].innerHtml.replaceAll(RegExp("[(|)|℃]"), ""));
//We can also do document.getElementsByTagName("td") but I am just being more specific here.
var rows = document.getElementsByTagName("table")[0].getElementsByTagName("td");
//Map elememt to its innerHtml, because we gonna need it.
//Iterate over all the table-data and store it in the data list
rows.map((e) => e.innerHtml).forEach((element) {
if(element != "-"){
data.add(element);
}
});
//print the data to console.
print(data);
}
Here's the sample output -
[Now, 19.8, 23, 93%, south 2.2km/h]
Hope it helps!
This article would probably be of help. It specifically uses the html package parser.
Following the example in the package's readme you can easily obtain a Document object. With this object you can obtain specific Elements of the DOM with methods like getElementById, getElementsByClassName, and getElementsByTagName. From there you can obtain the innerHtml of each Element that is returned and put together the output string you desire.
Related
I have some tabular data with the headers ('Type', 'Name'). I would like to select all items in column 'name', to check if they contain a search string. Each item in that column has the role 'gridcell', and the description 'Name'. See attached image1.
getByRole('gridcell', {description: /name/i}) doesn't work. I've looked through the typescript declarations of the queries and nothing seems helpful. How can one accomplish this?
Use getAllByRole('cell', {description: /name/i}) to retrieve an array containing the cells in column Name.
Check the array contains a certain value using toContain(item).
https://jestjs.io/docs/expect#tocontainitem
An example (using React):
'App.js'
function App() {
return (
<div className='App'>
<table>
<thead>
<tr>
<td id='name'>Name</td>
</tr>
</thead>
<tbody>
<tr>
<td aria-describedby='name'>J Blogs</td>
</tr>
<tr>
<td aria-describedby='name'>J Doe</td>
</tr>
<tr>
<td aria-describedby='name'>J Hancock</td>
</tr>
</tbody>
</table>
</div>
);
}
export default App;
'App.test.js'
import { render, screen } from '#testing-library/react';
import App from './App';
test('retrieves all cells described by name', () => {
render(<App />);
const cells = screen.getAllByRole('cell', {description: /name/i});
const cellValues = cells.map(cell => cell.textContent);
expect(cellValues).toContain('J Doe');
});
I'm fairly new to using Selenium Remote Driver and Perl. What I'd like to do is to have Selenium find all elements on a page using a partial match of text. Then store the full text of those elements into an array.
I've tried using:
#elements = $driver->find_elements("//tbody/tr[td[2]/div/span[2][contains(text(),'matching text')]]")->get_text;
However, this doesn't seem to work.
I've also tried:
#elements = $driver->find_elements("//tbody/tr[td[2]/div/span[2][contains(text(),'matching text')]]");
This does populate the array with webelements.
my #elements;
my #elementtext;
my $elementtext;
#elements = $driver->find_elements("//tbody/tr[td[2]/div/span[2][contains(text(),'matching text')]]");
foreach my $currentelement (#elements) {
$elementtext = $driver->find_element($currentelement)->get_text();
push #elementtext, $elementtext;
}
This causes perl to generate an error because webdriver can't find the element. Any ideas on what I'm doing wrong and how to fix it? I suspect that the problem is with the contents of the #elements array not actually being xpath elements.
Here is an example of the html:
<td>
<div class='cellContent'>Atlanta</div>
</td>
<td>
<div class='cellContent'>City</div>
</td>
<td>
<div class='cellContent'>Georgia</div>
</td>
<td class='sort_column'>
<div class='cellContent'>USA</div>
</td>
</tr>
<tr>
<td>
<div class='cellContent'>Joe Passenger</div>
</td>
<td>
<div class='cellContent'> <span>NFL</span>
<span>matching text: Atlanta.Falcons.team</span>
</div>
</td>
I want to get 'matching text: Atlanta.Falcons.team' stored into the array.
you can directly point to span tag using this xpath.
//tbody/tr/td/div/span[contains(text(),'matching text')]
I have seen questions pertaining to accordion but not entirely to my specific need. My table is populated using spacebars, more specific a nested each loop like this:
<tbody>
{{#each piece in pieces}}
<tr id="{{piece._id}}" class="itemList table-warning">
<th class="name tText">{{piece.name}} {{piece._id}}</th>
<td class="pdf tText" style="text-align: center"><a class ="pdf" href="{{piece.pdf}}" target="_blank"><i class="fa fa-file-text-o" aria-hidden="true"></i></a></td>
<td class="audio tText" style="text-align: center"><a class="audio" href="{{piece.audio}}" target="_blank"><i class="fa fa-volume-up" aria-hidden="true"></i></a></td>
<td class="format tText">{{piece.instrumentation}}</td>
<th class="price tText" >${{piece.price}}</th>
<td><input class ="qty" type ="number" name ="quantity" value="0" min="0"></td>
</tr>
<!-- Row that is being clicked-->
<tr class="partsList">
<td colspan="3"></td>
<th class="partName tText">{{piece.name}} Parts</th>
<td colspan="2"></td>
</tr>
{{#each part in piece.parts}}
<!-- Rows that should accordion -->
<!-- Currently ALL rows accordion on click. Need to accordion based on _id-->
<tr class="partList">
<td colspan="3"></td>
<td class="pname tText">{{piece.name}}: {{part.pname}}</td>
<td class="price tText">${{part.pprice}}</td>
<td><input class="qty" type="number" name="quantity" value="0" min="0"></td>
</tr>
{{/each}}
{{/each}}
</tbody>
I have a click function like so:
'click .partsList': function(e){
e.preventDefault();
$('.partList').nextUntil('tr.itemList').toggle();
}
The accordion function works, however it works with every instance of the each loop. i.e. every tr class ="partsList" will accordion at the same time on click.
To my understanding of the each loop, I can access the _id of a document using {{piece._id}}. If I set the table row id to equal that however, it only reads the _id of the FIRST document in the collection.
What I need is on click for the <tr class="partList"> to accordion based on _id. Or perhaps you would go about this a different way than bootstrap tables?
Please let me know if my question needs clarification.
You could filter the clicked .partslist using a data-* attribute. This causes jQuery to select only this specific items. Note that you need to attach the data-* attribute to the row that is clicked and to the rows that should collapse:
<tbody>
{{#each piece in pieces}}
...
<!-- Row that is being clicked-->
<!-- use the _id value of the piece context as data attribute -->
<tr class="partsList" data-id="{{piece._id}}">
<td colspan="3"></td>
<th class="partName tText">{{piece.name}} Parts</th>
<td colspan="2"></td>
</tr>
{{#each part in piece.parts}}
<!-- Rows that should accordion -->
<!-- Currently ALL rows accordion on click. Need to accordion based on _id-->
<!-- use the _id value of the piece context as data attribute -->
<tr class="partList" data-target="{{piece._id}}">
...
</tr>
{{/each}}
{{/each}}
</tbody>
'click .partsList': function(e, templateInstance){
e.preventDefault();
// get the data-id attribute of the clicked row
const targetId = templateInstance.$(e.currentTarget).data('id')
// skip if this row is not intended to toggle
if (!targetId) return
// toggle based on data-target attribute
templateInstance.$(`.partList[data-target="${targetId}"]`).nextUntil('tr.itemList').toggle();
}
I am new to wicket ,Please someone help me with a thought. I have a logic around a checkbox to display or not to display.
Problem:
when the logic of not to display a checkbox is on , which is by adding a display:none to the checkbox element dynamcially in code , there is a white space because of td surronding the checkbox.
my html looks like
<span wicket:id="checkgroup">
<table>
<tr wicket:id="srow" >
<td><input type="checkbox" wicket:id="scheck"/></td>
<td><img wicket:id="sicon"></img></td>
</tr>
</table>
</span>
so in code I have if else logic for adding a display:none to check box element which removes the checkbox from the view which looks like the below
<span wicket:id="checkgroup">
<table>
<tr wicket:id="srow" >
<td><input type="checkbox" wicket:id="scheck" style="display:none"/></td>
<td><img wicket:id="sicon"></img></td>
</tr>
</table>
</span>
final CheckGroup<Scope> checkGroup = new CheckGroup<>("checkGroup",
new ArrayList<> ());
ListView<Scope> listView = new ListView<Scope>
("srow", sList);
#Override
protected void populateItem(final ListItem<S> item)
{
Check<S> check = new Check<>("scheck", item.getModel(), checkGroup);
if(defaultscope)
{
check.add(new AttributeModifier("style","display:none"));
}
item.add(check);
}
so now my checkbox disappears but the surrounding td stays and causing a white space in display.
Any ideas on how to approach this issue.
Thanks.
You can use <wicket:enclosure> to remove html if the referenced child is not present. wicket enclosure.
Your code in populateItem could look like this:
Check<S> check = new Check<>("scheck", item.getModel(), checkGroup);
if(defaultscope)
{
check.setVisible(false);
}
item.add(check);
Your markup would look like this:
<tr wicket:id="srow" >
<wicket:enclosure>
<td><input type="checkbox" wicket:id="scheck"/></td>
</wicket:enclosure>
<td><img wicket:id="sicon"></img></td>
</tr>
I'm a beginner and I'm trying to write a Selenium web driver. I'm using eclipse and trying to locate a link available in next column. In each row I have different link. For example in my employee data table I have 2 columns and 10 rows in one page. The first column contains the name of person and second column contains its employee ID (ID is a hyperlink). I'm trying to select the hyperlink of any employee but I'm not able to do it.
I have below the HTML code and sample script.
<span id="37">
<div class="clear"></div>
<div id="FC_Schema.1021.WIP" type="DataCheckingList" name="FC_Schema.1021.WIP">
<input id="baseurl" type="hidden" value="/Web/" name="baseurl">
<input id="hdnDcCnt" type="hidden" value="13" name="hdnDcCnt">
<input id="PageNo" type="hidden" value="1" name="PageNo">
<meta content="width=device-width" name="viewport">
<style type="text/css">
<div id="DataCheckingLoad">
<div id="SupplyChainTabs">
<div id="gbo" class="InnerAlertsTabs">
<table id="one" class="draggable" width="100%">
<thead>
<tbody>
<tr>
<td valign="top" align="center">
<td valign="top">
<td valign="top">
<a onclick="return ButtonClick(this,'TxnyD.Communities.2.1','Org.2000476_Product.THQS|SMS|Questionnaire.WIP_Questionnaire_TxnyD.Communities.2.1_THQS_TxnyD.Operationaloffice.1.2');" href="#f">Axiom
Process LLC</a>
<div class="country-name">
<div class="CompanyInfoContactLinks">
</td>
<td valign="top">
THQS
<div class="clear"> </div>
<a id="Org.2000476_Product.THQS|SMS|Questionnaire.WIP_Questionnaire_TxnyD.Communities.2.1_THQS_TxnyD.Operationaloffice.1.2" onclick="RedirectToQuestionnairePage(id)" href="#">THQS</a>
<div class="clear"> </div>
</td>
In the above code first column contains company name i.e "Axiom
Process LLC" and second column contains company subcription name i.e."THQS". I have to select the THQS link of company "Axiom Process LLC"
Selenium script designed for it as below
public static void main(String[] args) throws Exception {
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://XXX.XXX.XXX.XXX/Web");
Thread.sleep(1000);
driver.findElement(By.xpath("//input[#id='UserName']")).sendKeys("Gbouser.1");
driver.findElement(By.xpath("//input[#id='Password']")).sendKeys("****");
driver.findElement(By.xpath("//input[#name='Login']")).click();
driver.findElement(By.xpath("//a[contains(text(),'Task')]")).click();
driver.findElement(By.xpath("//a[contains(text(),'Data Checking')]")).click();
driver.findElement(By.partialLinkText("Axiom")).findElement(By.xpath("//a[contains(text(),'THQS')]")).click();
}
So basically these are dynamic tables and each time it will have different records. How can select the link available in column?
I also tried below script as well:
driver.findElement(By.name("*[id^='CLS'][id$='Demolition Limited']")).findElement(By.xpath("//a[contains(text(),'THQS')])[3]")).click();
welcome to Stackoverflow. Before answering your question, just a few pointers. Think that you had a downvote 'cause you didn't format your question well. Otherwise a perfectly legal question, and you would receive help much earlier.
Secondly, don't ever put the real Web site address, username and password :). I was able to login, and understand exactly what you need, but a malicious guy could do bad wonders there.
To answer your question, instead of the line that is causing you problems, try this
Thread.sleep(3000);
TablePageObject tablePageObject = PageFactory.initElements(driver, TablePageObject.class);
tablePageObject.clickLink("Axiom");
Where TablePageObject is
public class TablePageObject {
private WebDriver driver;
#FindBy(css = "table tr")
private List<WebElement> allTableRows; // find all the rows of the table
public TablePageObject(WebDriver driver) {
this.driver = driver;
}
public void clickLink(String companyName) {
for(WebElement row : allTableRows) {
List<WebElement> links = row.findElements(By.cssSelector("a"));
// the first link by row is the company name, the second is link to be clicked
if (links.get(0).getText().contains(companyName)) {
links.get(3).click();
}
}
}
}
An explanation, TablePageObject class will be your programmatic handle for the dynamic table you're trying to control. It follows a page factory pattern of selenium, which I heartly recommend, and you can learn more here https://code.google.com/p/selenium/wiki/PageFactory
It basically keeps a collection of rows of your table, which more or less looks like:
<tr>
<td valign="top" align="center">
// irelevant
</td>
<td valign="top">
// irelevant
</td>
<td valign="top">
<a>Axiom Process LLC</a>
<a>company details</a>
<a>web details</a>
</td>
<td valign="top">
<a>THQS</a>
</td>
<td valign="top" align="center" style="display: none">
// irelevant
</td>
<td valign="top">
//irelevant
</td>
<td valign="top">
// irelevant
</td>
<td valign="top">
</td>
<td>
</td>
</tr>
You collect all the links from the table, check the company name against the first link, and if matched, click the fourth link,
Hope it helps, best,
by the way, I've masked your password in the question