Scrapy css selector not getting text in <i></i> - scrapy

I am a newbie trying to scrape some quotes from goodreads.com but can't get the text = ... part working properly.
I'm not sure what I'm missing so would appreciate some help.
for quote in response.css("div.quoteDetails"):
text = quote.css("div.quoteText:not(.authorOrTitle)::text").getall() # not getting <i>
author = quote.css("span.authorOrTitle::text").get().strip()
book = quote.css("a.authorOrTitle::text").get()
tags = quote.css("div.quoteFooter div.left a::text").getall()
print(dict(text=text, author=author, book=book, tags=tags))
I have tried some permutations like text = quote.css("div.quoteText :not(span):not(script) ::text").getall()
The closest I've managed is with text = quote.css("div.quoteText:not(.authorOrTitle)::text").getall() which returned (missing <i>smiles all the time</i>)
{'text': ["\n “God does not play dice with the universe; He plays an ineffable game of His own devising, which might be compared, from the perspective of any of the other players [i.e. everybody], to being involved in an obscure and complex variant of poker in a pitch-dark room, with blank cards, for infinite stakes, with a Dealer who won't tell you the rules, and who ", '.”\n ', ' ―\n ', '\n ', '\n \n\n\n', '\n\n'],
'author': 'Terry Pratchett,',
'book': 'Good Omens: The Nice and Accurate Prophecies of Agnes Nutter, Witch',
'tags': ['einstein', 'gaiman', 'god', 'humor']}
html snippet from the page I want to scrape https://www.goodreads.com/quotes/tag/god?page=1
<div class="quoteDetails ">
<a class="leftAlignedImage" href="/author/show/1654.Terry_Pratchett">
<img alt="Terry Pratchett" src="https://images.gr-assets.com/authors/1235562205p2/1654.jpg">
</a>
<div class="quoteText">
“God does not play dice with the universe; He plays an ineffable game of His own devising, which might be compared, from the perspective of any of the other players [i.e. everybody], to being involved in an obscure and complex variant of poker in a pitch-dark room, with blank cards, for infinite stakes, with a Dealer who won't tell you the rules, and who <i>smiles all the time</i>.”
<br> ―
<span class="authorOrTitle">
Terry Pratchett,
</span>
<span id="quote_book_link_12067">
<a class="authorOrTitle" href="/work/quotes/4110990">Good Omens: The Nice and Accurate Prophecies of Agnes Nutter, Witch</a>
</span>
<script>
//<![CDATA[
var newTip = new Tip($('quote_book_link_12067'), "\n\n <h2><a class=\"readable bookTitle\" href=\"https://www.goodreads.com/book/show/12067.Good_Omens?from_choice=false&from_home_module=false\">Good Omens: The Nice and Accurate Prophecies of Agnes Nutter, Witch<\/a><\/h2>\n\n <div>\n by <a class=\"authorName\" href=\"/author/show/1654.Terry_Pratchett\">Terry Pratchett<\/a>\n <\/div>\n\n <div class=\"smallText uitext darkGreyText\">\n <span class=\"minirating\"><span class=\"stars staticStars notranslate\"><span size=\"12x12\" class=\"staticStar p10\"><\/span><span size=\"12x12\" class=\"staticStar p10\"><\/span><span size=\"12x12\" class=\"staticStar p10\"><\/span><span size=\"12x12\" class=\"staticStar p10\"><\/span><span size=\"12x12\" class=\"staticStar p3\"><\/span><\/span> 4.24 avg rating — 595,193 ratings<\/span> — published 1990\n <\/div>\n\n <div class=\"addBookTipDescription\">\n \n<span id=\"freeTextContainer8297402955929030295\">‘Armageddon only happens once, you know. They don’t let you go around again until you get it right.’\n\nPeople have been predicting the end of the world almost from its very beginning, so it’s only natural to be sceptical when a new date is set for Jud<\/span>\n <span id=\"freeText8297402955929030295\" style=\"display:none\">‘Armageddon only happens once, you know. They don’t let you go around again until you get it right.’\n\nPeople have been predicting the end of the world almost from its very beginning, so it’s only natural to be sceptical when a new date is set for Judgement Day. But what if, for once, the predictions are right, and the apocalypse really is due to arrive next Saturday, just after tea?\n\nYou could spend the time left drowning your sorrows, giving away all your possessions in preparation for the rapture, or laughing it off as (hopefully) just another hoax. Or you could just try to do something about it.\n\nIt’s a predicament that Aziraphale, a somewhat fussy angel, and Crowley, a fast-living demon now finds themselves in. They’ve been living amongst Earth’s mortals since The Beginning and, truth be told, have grown rather fond of the lifestyle and, in all honesty, are not actually looking forward to the coming Apocalypse.\n\nAnd then there’s the small matter that someone appears to have misplaced the Antichrist…<\/span>\n <a data-text-id=\"8297402955929030295\" href=\"#\" onclick=\"swapContent(\$(this));; return false;\">...more<\/a>\n\n <\/div>\n\n <div class=\'wtrButtonContainer wtrSignedOut\' id=\'10_book_12067\'>\n<div class=\'wtrUp wtrLeft\'>\n<form action=\"/shelf/add_to_shelf\" accept-charset=\"UTF-8\" method=\"post\"><input name=\"utf8\" type=\"hidden\" value=\"✓\" /><input type=\"hidden\" name=\"authenticity_token\" value=\"eHxnso0cZ8mac56WZu5b+f9QTJuvU6CbzkAY03nf4vcdXMimazuX3oOLs4umgVsafX94R4eGUAdsRhvwmfdIaA==\" />\n<input type=\"hidden\" name=\"book_id\" id=\"book_id\" value=\"12067\" />\n<input type=\"hidden\" name=\"name\" id=\"name\" value=\"to-read\" />\n<input type=\"hidden\" name=\"unique_id\" id=\"unique_id\" value=\"10_book_12067\" />\n<input type=\"hidden\" name=\"wtr_new\" id=\"wtr_new\" value=\"true\" />\n<input type=\"hidden\" name=\"from_choice\" id=\"from_choice\" value=\"false\" />\n<input type=\"hidden\" name=\"from_home_module\" id=\"from_home_module\" value=\"false\" />\n<input type=\"hidden\" name=\"ref\" id=\"ref\" value=\"\" class=\"wtrLeftUpRef\" />\n<input type=\"hidden\" name=\"existing_review\" id=\"existing_review\" value=\"false\" class=\"wtrExisting\" />\n<input type=\"hidden\" name=\"page_url\" id=\"page_url\" value=\"/quotes/tag/god\" />\n<button class=\'wtrToRead\' type=\'submit\'>\n<span class=\'progressTrigger\'>Want to Read<\/span>\n<span class=\'progressIndicator\'>saving…<\/span>\n<\/button>\n<\/form>\n\n<\/div>\n\n<div class=\'wtrRight wtrUp\'>\n<form class=\"hiddenShelfForm\" action=\"/shelf/add_to_shelf\" accept-charset=\"UTF-8\" method=\"post\"><input name=\"utf8\" type=\"hidden\" value=\"✓\" /><input type=\"hidden\" name=\"authenticity_token\" value=\"SKP2jUje5gC8x8+/fKoz/fZEAz53hITka0SMTXDRT2Etg1mZrvkWF6U/4qK8xTMedGs34l9RdHjJQo9ukPnl/g==\" />\n<input type=\"hidden\" name=\"unique_id\" id=\"unique_id\" value=\"10_book_12067\" />\n<input type=\"hidden\" name=\"book_id\" id=\"book_id\" value=\"12067\" />\n<input type=\"hidden\" name=\"a\" id=\"a\" />\n<input type=\"hidden\" name=\"name\" id=\"name\" />\n<input type=\"hidden\" name=\"from_choice\" id=\"from_choice\" value=\"false\" />\n<input type=\"hidden\" name=\"from_home_module\" id=\"from_home_module\" value=\"false\" />\n<input type=\"hidden\" name=\"page_url\" id=\"page_url\" value=\"/quotes/tag/god\" />\n<\/form>\n\n<button class=\'wtrShelfButton\'><\/button>\n<\/div>\n\n<div class=\'ratingStars wtrRating\'>\n<div class=\'starsErrorTooltip hidden\'>\nError rating book. Refresh and try again.\n<\/div>\n<div class=\'myRating uitext greyText\'>Rate this book<\/div>\n<div class=\'clearRating uitext\'>Clear rating<\/div>\n<div class=\"stars\" data-resource-id=\"12067\" data-user-id=\"0\" data-submit-url=\"/review/rate/12067?page_url=%2Fquotes%2Ftag%2Fgod&rate_books_page=false&stars_click=false&wtr_button_id=10_book_12067\" data-rating=\"0\"><a class=\"star off\" title=\"did not like it\" href=\"#\" ref=\"\">1 of 5 stars<\/a><a class=\"star off\" title=\"it was ok\" href=\"#\" ref=\"\">2 of 5 stars<\/a><a class=\"star off\" title=\"liked it\" href=\"#\" ref=\"\">3 of 5 stars<\/a><a class=\"star off\" title=\"really liked it\" href=\"#\" ref=\"\">4 of 5 stars<\/a><a class=\"star off\" title=\"it was amazing\" href=\"#\" ref=\"\">5 of 5 stars<\/a><\/div>\n<\/div>\n\n<\/div>\n\n\n\n\n", { style: 'addbook', stem: 'leftMiddle', hook: { tip: 'leftMiddle', target: 'rightMiddle' }, offset: { x: 5, y: 0 }, hideOn: false, width: 400, hideAfter: 0.05, delay: 0.35 });
$('quote_book_link_12067').observe('prototip:shown', function() {
if (this.up('#box')) {
$$('div.prototip').each(function(i){i.setStyle({zIndex: $('box').getStyle('z-index')})});
} else {
$$('div.prototip').each(function(i){i.setStyle({zIndex: 6000})});
}
});
newTip['wrapper'].addClassName('prototipAllowOverflow');
$('quote_book_link_12067').observe('prototip:shown', function () {
$$('div.prototip').each(function (e) {
if ($('quote_book_link_12067').hasClassName('ignored')) {
e.setStyle({'display': 'none'});
return;
}
e.setStyle({'overflow': 'visible'});
});
});
$('quote_book_link_12067').observe('prototip:hidden', function () {
$$('span.elementTwo').each(function (e) {
if (e.getStyle('display') !== 'none') {
var lessLink = e.next();
swapContent(lessLink);
}
});
});
//]]>
</script>
</div>
<div class="quoteFooter">
<div class="greyText smallText left">
tags:
einstein,
gaiman,
god,
humor
</div>
<div class="right">
<a class="smallText" title="View this quote" href="/quotes/11285-god-does-not-play-dice-with-the-universe-he-plays">2464 likes</a>
</div>
</div>
</div>

I could not figure out how to do it using css selector so I used xpath path selector. Then I used MapCompose to remove the whitespace and join.
#spider.py snippet
def parse(self, response):
for quote in response.css("div.quoteDetails"):
l = ItemLoader(GoodreadsItem(), quote)
l.add_xpath("text", './/div[#class="quoteText"]/text() | .//div[#class="quoteText"]/i/text()')
yield l.load_item()
#items.py snippet
class GoodreadsItem(scrapy.Item):
text = scrapy.Field(
input_processor=MapCompose(lambda string: string.strip()),
output_processor=Join()
)

Related

VueJS unexpectedly runs a function

Hello guys specially VueJS devs theres something weird happened. Ill explain it one by one
Full video:
https://drive.google.com/file/d/1G2ksQsMQ1LB868dg29f8mm4NR_x5GycF/view?fbclid=IwAR1YmYbo3J6jHrY6PHd8E_lxA47VJSXV6G3132_uF6Or3bXv7MbnQbRvKaU
I use datatable and then i use this getDefaultPrice() to manipulate the price because the format of my price is like this ("65;75") to return the first value to PHP 65.00
then once i click the add to cart button please see image for codes the getDefaultPrice() also executed.
and I received an error "price.split is not a function" I tried to console.log the function and it really runs it without calling it in my add_to_cart();
<td>
<p>{{getDefaultPrice(product.price)}}</p>
</td>
<td>
<button
class="btn main_bg_color add_to_cart_btn" data-toggle="modal" data-target="#productModal"
#click="add_to_cart(product)"
>
<i class="fa fa-shopping-cart"></i> Add to cart
</button>
</td>
add_to_cart(product) {
this.modal_data = [];
this.modal_data.push(product)
this.modal_data[0].variation = this.modal_data[0].variation.split(';');
this.modal_data[0].price = this.modal_data[0].price.split(';');
this.modal_data[0].drinks_price = this.modal_data[0].drinks_price.split(';');
this.modal_data[0].drinks = this.modal_data[0].drinks.split(';');
},
getDefaultPrice(price) {
console.log("test")
var price_arr = price.split(";");
var default_price = parseFloat(price_arr[0]);
return "PHP " + default_price.toFixed(2);
},

call function since product-variants.tpl Prestashop

I'm creating a web in Prestashop and my problem is the next:
I has created a new table in db (mysql) called 'tallas' and I have the size's preferences of the users. Now, I need call this table since the page product-variants.tpl because I would like to put cheeked for default the option select by the customer.
I create this function in classes/Product.php
public function getTalla($id_customer){
$result = Db::getInstance()->ExecuteS('
SELECT `talla1`
FROM `tallas`
WHERE `cliente` = `$id_customer`');
return $result;
}
ok, I would like to receive for parameters the user id (I don't know how to do that yet) and I would like to receive the value of talla1 and then I would like put cheeked the option selected by the customer here in the themes/asmart/templates/catalog/_partials/product-variants.tpl in the radio.
<li class="float-xs-left input-container">
<label>
<input class="input-color" type="radio" data-product-attribute="{$id_attribute_group}" name="group[{$id_attribute_group}]" value="{$id_attribute}"{if $group_attribute.selected} checked="checked"{/if}>
<span
{if $group_attribute.html_color_code}class="color" style="background-color: {$group_attribute.html_color_code}" {/if}
{if $group_attribute.texture}class="color texture" style="background-image: url({$group_attribute.texture})" {/if}
><span class="sr-only">{$group_attribute.name}</span></span>
</label>
</li>
Sincerely I don't know any idea to how to do that, can someone help me?
UPDATE: The problem is solved!
The problem is solved. I do that:
in classes/Product.php
public function getTalla(){
$variable = Context::getContext()->customer->id;
$result = Db::getInstance()->ExecuteS('SELECT * FROM `tallas` WHERE `cliente` = `$variable`');
return $result;
}
in ProductController.php
$this->context->smarty->assign('images_ex',$this->product->getTalla());
in product-variants.tpl
{if $images_ex[0]['talla1'] == $group_attribute.name} checked="checked"{/if}
I hope this can help someone in the future.

How to enable the Google Trusted Stores without having Platinum Level in Bigcommerce

I would like to enable the Google Trusted Stores code without having to subscribe to the Platinum Level (I'm on a Gold Level plan). I have successfully set up automated daily Shipping and Cancellation Feeds through ShipWorks. I believe I set up the "Badge" code correctly on the footer.html:
<!-- BEGIN: Google Trusted Stores -->
<script type="text/javascript">
var gts = gts || [];
gts.push(["id", "######"]);
gts.push(["badge_position", "BOTTOM_RIGHT"]);
gts.push(["locale", "en_AU"]);
gts.push(["google_base_offer_id", "%%GLOBAL_ProductId%%"]);
gts.push(["google_base_subaccount_id", "8669332"]);
gts.push(["google_base_country", "AU"]);
gts.push(["google_base_language", "en_AU"]);
(function() {
var gts = document.createElement("script");
gts.type = "text/javascript";
gts.async = true;
gts.src = "https://www.googlecommerce.com/trustedstores/api/js";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(gts, s);
})();
</script>
<!-- END: Google Trusted Stores -->
I have to put the Order Confirmation Module Code on the website. The issue is figuring out the Est. Ship Date and Est. Delivery Date and putting in a "loop" to get the requested data for each item in the order. I have placed the following code on the order.html page:
<!-- start order and merchant information -->
<span id="gts-o-id">%%GLOBAL_OrderId%%</span>
<span id="gts-o-domain">www.****.com.au</span>
<span id="gts-o-email">%%GLOBAL_CurrentCustomerEmail%%</span>
<span id="gts-o-country">%%GLOBAL_ShipCountry%%</span>
<span id="gts-o-currency">%%GLOBAL_CurrencyName%%</span>
<span id="gts-o-total">%%GLOBAL_OrderTotal%%</span>
<span id="gts-o-discounts">%%GLOBAL_CouponDiscount%%</span>
<span id="gts-o-shipping-total">%%GLOBAL_ShippingPrice%%</span>
<span id="gts-o-tax-total">%%GLOBAL_TaxCost%%</span>
<span id="gts-o-est-ship-date">ORDER_EST_SHIP_DATE</span>
<span id="gts-o-est-delivery-date">ORDER_EST_DELIVERY_DATE</span>
<span id="gts-o-has-preorder">N</span>
<span id="gts-o-has-digital">N</span>
<!-- end order and merchant information -->
<!-- start repeated item specific information -->
<!-- item example: this area repeated for each item in the order -->
<span class="gts-item">
<span class="gts-i-name">%%GLOBAL_ProductName%%</span>
<span class="gts-i-price">%%GLOBAL_ProductPrice%%</span>
<span class="gts-i-quantity">%%GLOBAL_ProductQuantity%%</span>
<span class="gts-i-prodsearch-id">%%GLOBAL_ProductId%%</span>
<span class="gts-i-prodsearch-store-id">######</span>
<span class="gts-i-prodsearch-country">AU</span>
<span class="gts-i-prodsearch-language">en_AU</span>
</span>
<!-- end item 1 example -->
<!-- end repeated item specific information -->
</div>
<!-- END Google Trusted Stores Order -->
I have tried with the code for the badge and successfully got approved. as far as the conversion module. I had to do a "Hack" with javascript for the EST ship date and EST delivery date:
<!-- Include the conversion tracking code for all analytics packages -->
<!-- START Google Trusted Stores Order -->
<div id="gts-order" style="display:none;" translate="no">
<!-- start order and merchant information -->
<span id="gts-o-id">%%ORDER_ID%%</span>
<span id="gts-o-domain">www.doubletakeshapewear.com</span>
<span id="gts-o-email">%%ORDER_EMAIL%%</span>
<span id="gts-o-country">%%GLOBAL_ShipCountry%%</span>
<span id="gts-o-currency">%%GLOBAL_CurrencyName%%</span>
<span id="gts-o-total">%%ORDER_AMOUNT%%</span>
<span id="gts-o-discounts">%%GLOBAL_CouponDiscount%%</span>
<span id="gts-o-shipping-total">%%GLOBAL_ShippingPrice%%</span>
<span id="gts-o-tax-total">%%GLOBAL_TaxCost%%</span>
<span id="gts-o-est-ship-date"></span>
<script>
var today = new Date();
var tomorrow = new Date();
tomorrow.setDate(today.getDate()+3);
if(tomorrow.getMonth() <= 8){
var fecha = tomorrow.getFullYear()+'-'+'0'+(tomorrow.getMonth()+1)+'-'+tomorrow.getDate();
} else{
var fecha = tomorrow.getFullYear()+'-'+(tomorrow.getMonth()+1)+'-'+tomorrow.getDate();
}
document.getElementById("gts-o-est-ship-date").innerHTML = fecha;
</script>
<span id="gts-o-est-delivery-date"></span>
<script>
var today2 = new Date();
var tomorrow2 = new Date();
var j =document.getElementById("gts-o-country").innerHTML;
if( j != 'US'){
if(
tomorrow2.setDate(today.getDate()+4);
if(tomorrow2.getMonth() <= 8){
var fecha2 = tomorrow2.getFullYear()+'-'+'0'+(tomorrow2.getMonth()+1)+'-'+tomorrow2.getDate();
} else{
var fecha2 = tomorrow2.getFullYear()+'-'+(tomorrow2.getMonth()+1)+'-'+tomorrow2.getDate();
}
document.getElementById("gts-o-est-delivery-date").innerHTML = fecha2;
}else{
tomorrow2.setDate(today.getDate()+20);
if(tomorrow2.getMonth() <= 8){
var fecha2 = tomorrow2.getFullYear()+'-'+'0'+(tomorrow2.getMonth()+1)+'-'+tomorrow2.getDate();
} else{
var fecha2 = tomorrow2.getFullYear()+'-'+(tomorrow2.getMonth()+1)+'-'+tomorrow2.getDate();
}
document.getElementById("gts-o-est-delivery-date").innerHTML = fecha2;
}
</script>
<span id="gts-o-has-preorder">N</span>
<span id="gts-o-has-digital">N</span>
<!-- end order and merchant information -->
<!-- start repeated item specific information -->
<!-- item example: this area repeated for each item in the order -->
<span class="gts-item">
<span class="gts-i-name">%%GLOBAL_ProductName%%</span>
<span class="gts-i-price">%%GLOBAL_ProductPrice%%</span>
<span class="gts-i-quantity">%%GLOBAL_ProductQuantity%%</span>
<span class="gts-i-prodsearch-id">%%GLOBAL_ProductId%%</span>
<span class="gts-i-prodsearch-store-id">483911</span>
<span class="gts-i-prodsearch-country">US</span>
<span class="gts-i-prodsearch-language">en_US</span>
</span>
<!-- end item 1 example -->
<!-- end repeated item specific information -->
</div>
<!-- END Google Trusted Stores Order -->
I put this under the order.html I'm checking some other options because your code is uncomplete on the delivery date and ship date. when I spoke with some bigcommerce people they said that this variables are populated from customer information that is given when you are platinum ( which means that they don't even exist on bigcommerce )
Please let me know if you find something else or if it works for you. also please don't forget to purchase and install your own ssl
In my experience with Bigcommerce this is not possible. They have restricted the data which is required for GTS to only be available in the code that is output by their system, and not in other files. Basically, even if we knew what the variables were I don't believe they would work because they aren't a global scope.
I would guess that if you can use GTS to sell your products, the small price increase from their Gold to platinum level will quickly be made up in your sales.

How to get element with specific value in htmlagilitypack

I have ASP.NET MVC4 project where try to parse html document with HtmlAgilityPack. I have the following HTML:
<td class="pl22">
<p class='pb10 pt10 t_grey'>Experience:</p>
<p class='bold'>any</p>
</td>
<td class='pb10 pl20'>
<p class='t_grey pb10 pt10'>Education:</p>
<p class='bold'>any</p>
</td>
<td class='pb10 pl20'>
<p class='pb10 pt10 t_grey'>Schedule:</p>
<p class='bold'>part-time</p>
<p class='text_12'>2/2 (day/night)</p>
</td>
I need to get values:
"any" after "Experience:"
"any" after "Education:"
"part-time", "2/2 (day/night)" after "Schedule:"
All what I imagine is that
HtmlNode experience = hd.DocumentNode.SelectSingleNode("//td[#class='pl22']//p[#class='bold']");
But it get me different element, which place in the top of the page. My Experience, Education and Schedule is static values. In additional my any, any part-time day/night is the dynamic values. Can anybody help me?
Below is an alternative which is more focused on the table headers (Experience, Education and Schedule), instead of the node classes:
private static List<string> GetValues(HtmlDocument doc, string header) {
return doc.DocumentNode.SelectNodes(string.Format("//p[contains(text(), '{0}')]/following-sibling::p", header)).Select(x => x.InnerText).ToList();
}
You can call that method like this:
var experiences = GetValues(doc, "Experience");
var educations = GetValues(doc, "Education");
var schedules = GetValues(doc, "Schedule");
experiences.ForEach(Console.WriteLine);
educations.ForEach(Console.WriteLine);
schedules.ForEach(Console.WriteLine);
You could do it something like this if you want to keep the XPath
var html = "<td class='pl22'><p class='pb10 pt10 t_grey'>Experience:</p><p class='bold'>any</p></td><td class='pb10 pl20'><p class='t_grey pb10 pt10'>Education:</p><p class='bold'>any</p></td><td class='pb10 pl20'><p class='pb10 pt10 t_grey'>Schedule:</p><p class='bold'>part-time</p><p class='text_12'>2/2 (day/night)</p></td> ";
var doc = new HtmlDocument
{
OptionDefaultStreamEncoding = Encoding.UTF8
};
doc.LoadHtml(html);
var part1 = doc.DocumentNode.SelectSingleNode("//td[#class='pl22']/p[#class='bold']");
var part2 = doc.DocumentNode.SelectNodes("//td[#class='pb10 pl20']/p[#class='bold']");
foreach (var item in part2)
{
Console.WriteLine(item.InnerText);
}
var part3 = doc.DocumentNode.SelectSingleNode("//td[#class='pb10 pl20']/p[#class='text_12']");
Console.WriteLine(part1.InnerText);
Console.WriteLine(part3.InnerText);
Output :
any
part-time
any
2/2 (day/night)

vBulletin 4.x External Page Login and Variables

I've been searching around and experimenting with this for hours, with no success.
I'm trying to login to vBulletin from an external page. I've managed to get this to work. However what I can't get to work is showing the username and any of the $vbulletin variables.
I've included global.php chdir() to the forum etc etc, but I just can't get it to work.
Does anyone know how to go about this?
This is working example i'm using it. Its working fine. Its show user name and logout button on External page.
I don't know why -vote it.
<?php
$curdir = getcwd();
#Add your root dir below where it says "ADD ROOT" Example: /home/server/public_html/mainsite/forums
#Do not end with a "/" leave it open like above example.
chdir('ADD ROOT');
require_once('ADD ROOT/global.php');
chdir($curdir);
if ($vbulletin->userinfo['userid'] == 0) {
#Form Display Code, You can edit the way the Form is layed out here.
echo "<form id=\"login\" action=\"/forums/login.php?do=login\" method=\"post\" onsubmit=\"md5hash(vb_login_password, vb_login_md5password, vb_login_md5password_utf, 0)\">
<script type=\"text/javascript\" src=\"clientscript/vbulletin_md5.js?v=364\"></script>
Register
<label for=\"navbar_username\">Username</label>
<input type=\"text\" class=\"bginput\" style=\"font-size: 11px\" name=\"vb_login_username\" id=\"navbar_username\" size=\"10\" accesskey=\"u\" tabindex=\"101\" onfocus=\"if (this.value == 'User Name') this.value = '';\" />
<label for=\"navbar_password\">Password</label>
<input type=\"password\" class=\"bginput\" style=\"font-size: 11px\" name=\"vb_login_password\" id=\"navbar_password\" size=\"10\" tabindex=\"102\" />
<label for=\"cb_cookieuser_navbar\"><input type=\"checkbox\" name=\"cookieuser\" value=\"1\" tabindex=\"103\" id=\"cb_cookieuser_navbar\" accesskey=\"c\" />Remember Me?</label>
<input type=\"submit\" class=\"button\" value=\"Login\" tabindex=\"104\" title=\"Enter your username and password in the boxes provided to login, or click the 'register' button to create a profile for yourself.\" accesskey=\"s\" />
<input type=\"hidden\" name=\"s\" value=\"\" />
<input type=\"hidden\" name=\"do\" value=\"login\" />
<input type=\"hidden\" name=\"vb_login_md5password\" />
<input type=\"hidden\" name=\"vb_login_md5password_utf\" />
</form>";
#End Form Display Code
} else {
#Display after login completed
echo "Welcome Back, <b>".$vbulletin->userinfo['username']."</b>";
if ($vbulletin->userinfo['usergroupid'] == '6' ) {
echo " | My Profile";
echo " | AdminCP";
echo " | ModCP";
}
}
?>